Java实现Arrays.asSet()

Google查询资料如下:
http://stackoverflow.com/questions/3064423/java-easily-convert-array-to-set
http://tech.puredanger.com/2007/04/05/arraysasset/


stackoverflow上提出了这个问题, 关于如何将数组转换成Set
最佳答案给出的是
Set<T> mySet=new HashSet<T>(Arrays.asList(someArray));


原来list可以作为参数来构建一个Set,
试着运行一下果然可以。
然后参考
代码如下:

public class SetTest2 
{
public static void main(String[] args)
{
String a="hello";
String b="world";

Set<String> mySet=asSet(a,b);

System.out.println(mySet);


}


public static <T> Set<T> asSet(T... values){
Set<T> mySet=new HashSet<T>(Arrays.asList(values));
return mySet;

}


}


输入结果: [hello, world]

---------------分割线----------------

这里的核心就是HashSet的构造函数,
[color=blue]Constructs a new set containing the elements in the specified collection. The HashMap is created with default load factor (0.75) and an initial capacity sufficient to contain the elements in the specified collection.

Parameters:
c the collection whose elements are to be placed into this set
[/color]

java.util.HashSet.HashSet(Collection<? extends String> c)

这里接受一个实现Collection接口的参数,而Collection后面的泛型则是由用户定义,
由于这里我们定义的是String, 所以这里就成了? extends String,就可以接受String类型了。

(关于Collection:The root interface in the collection hierarchy. 所有的集合的根接口)


这里的疑问就是public static <T> Set<T> asSet(T... values){
如果没有第一个<T>,便会报错。
错误如下:

[img]http://dl2.iteye.com/upload/attachment/0091/2162/5b62a200-d64f-3c8e-be18-077420ed16ce.jpg[/img]

在Hibernate源码里面也看到这种代码, 很不理解。
因为平时所学过的传统的代码都是例如:
public class BaseDao<T>
public List<T> list(para)
public T load(int id)

不明白static后面的<T>究竟定义了什么。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值