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 di开发者_开发百科fferent 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.
- Defining a collection (or any typed class) without specifying a type argument is called using a raw type. It exists only for backwards compatibility and should not be used in new code. If effectively removes all effects of generics on the type.
- Generally, you could define your set to accept
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) It means it can have any object. If you want to add any type. (Generally a design problem)
ii) Using type erasure you can.
But, as excepted, there's a run time error.
Getting an error at compile time is usually better than getting a runtime error. (Easier to find and fix)
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 do
Set vals = new Treeset();
String s = (String)vals.get(0);
instead of
Set<String> vals = new Treeset<String>();
String s = vals.get(0);
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.
private Set<JPanel> s1;
public void run() {
aMethod(s1);
}
/* line 7 */ public void aMethod(Set panels) {
}
If you refactor the above code by changing the 7th line to
public void aMethod(Set<Object> panels) {
it will no longer compile. If you refactor that line to
public void aMethod(Set<?> panels) {
it will still compile as before, and as an extra bonus you will no longer have the "Set is raw..." warning
精彩评论