用{}直接在new的时候就添加元素
HashSet<Integer> hash = new Hash<>(1); //correct
HashSet<Integer> hash = new Hash<>();
hash.add(1); //correct
HashSet<Integer> hash = new Hash<Integer>(){
{add(1);}
};
//correct
HashSet<Integer> hash = new Hash<>(){
{add(1);}
};
//compile error: <> cannot be used with anomynous class
查了一下说目前java版本不支持<>和匿名类一起用,but不能理解为什么HashSet hash = new Hash<>()就是正确的
本文探讨了使用不同方式初始化 Java 中的 HashSet 对象的方法,并解释了为何某些语法结构会导致编译错误。通过具体的代码示例,文章揭示了匿名内部类与泛型之间的限制。
2061

被折叠的 条评论
为什么被折叠?



