定义没有特定类型的集合
public static void main(String[] args) {
Set vals = new TreeSet();
vals.add("one");
vals.add(1);
vals.add("two");
System.out.println(vals);
}
(i)-定义一个集合而不给它一个类型意味着什么?出于什么目的 它是为了什么?
(ii)-我可以以任何方式向集合添加不同类型吗?
这是一个例子-尽管它警告我,但没有编译错误。
但是,正如例外,存在运行时错误。
public static void main(String[] args) {
Set vals = new TreeSet();
vals.add("one");
vals.add(1);
vals.add("two");
System.out.println(vals);
}
(i)-What does it mean to define a collection without giving it a type?For what purpose
does it made for?
(ii)-Can I add different type to the collection any way?
Here's an example- There's no compilation error, though it's warning me.
But, as excepted, there's a run time error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Object
:然后它将接受所有值:Set
Object
: it would then accept all values:Set<Object> vals = new HashSet<Object>()
. However this won't work forTreeSet
, because it needs its values to beComparable
with each other. If you want to add arbitrary types to the sameTreeSet
(which is usually a sign of some architecture problems, i.e. a design smell), then you'll need to implement your ownComparator
that can compare arbitrary elements and pass that into the appropriateTreeSet
constructor.i) 这意味着它可以有任何对象。如果你想添加任何类型。 (通常是设计问题)
ii)可以使用类型擦除。
在编译时得到错误通常比得到运行时错误要好。 (更容易查找和修复)
i) It means it can have any object. If you want to add any type. (Generally a design problem)
ii) Using type erasure you can.
Getting an error at compile time is usually better than getting a runtime error. (Easier to find and fix)
Java 1.4 之前还没有泛型。所有集合只能包含
Object
,并且在将对象从集合中取出后使用该对象时,必须对该对象进行类转换。因此,您应该这样做,而不是
放入没有共享接口或超类的不同类型的对象,这是非常糟糕的做法,因为当您将对象从集合中取出时,您将不知道如何处理该对象。
Upto Java 1.4 there were no Generics. All collections could only contain
Object
and you would have to classcast the object when using the object after taking it out of the collection. So you would doinstead of
Putting different types of objects that have no shared interface or superclass is very bad practice since you wont know how to handle the object when you take it out of the collection.
如果通过更改第 7 行来重构上面的代码,
它将不再编译。如果您重构该行,
它仍然会像以前一样编译,并且作为额外的好处,您将不再有“Set is raw...”警告
If you refactor the above code by changing the 7th line to
it will no longer compile. If you refactor that line to
it will still compile as before, and as an extra bonus you will no longer have the "Set is raw..." warning