开发者

Defining Collections without specific type

开发者 https://www.devze.com 2023-04-04 12:34 出处:网络
public static void main(String[] args) { Set vals = new TreeSet(); vals.add(\"one\"); vals.add(1); vals.add(\"two\");
    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.


  1. 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.
  2. 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 for TreeSet, because it needs its values to be Comparable with each other. If you want to add arbitrary types to the same TreeSet (which is usually a sign of some architecture problems, i.e. a design smell), then you'll need to implement your own Comparator that can compare arbitrary elements and pass that into the appropriate TreeSet 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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号