Java, Generics: What is the difference between Set <?> S = HashSet <String> () and Set s = HashSet <String> ()?

I read about unknown types and raw types in generics, and this question came to mind. In other words, this is ...

Set<?> s = new HashSet<String>();

and

Set s = new HashSet<String>();

... same?

I tried this, and they both seem to do the same thing, but I would like to know if they are different from the compiler.

+3
source share
4 answers

No, they are not the same. Here is the main difference:

Set<?> s = HashSet<String>();
s.add(2);  // This is invalid

Set s = HashSet<String>();
s.add(2);  // This is valid.

Point, the first is an unlimited parameterized type Set. The compiler will check there, and since you cannot add anything other than nullthese types, the compiler will give you an error.

, , -. , .

. 2 Set<?>, Set , , , , String.

, . , . , raw-, - static Class - Set.class, Set<?>.class.

+6

Set<?>, : " ". ( null), , .

, , , . .

, . Set<String> .

+5

generics, Set.

. , "a Set - ", , add, , , . , .

. - Set, String s, :

Set<String> genericSet = new HashSet<String>();
Set rawSet = genericSet;
rawSet.add(1);  // That not a String!

// Runtime error here.
for (String s : genericSet)
{
    // Do something here
}

ClassCastException, Integer 1, String.

- .

Set<String> s = HashSet<String>();
+3

Set<?> , , . , add(T).

Set , "" , . , , .

, . . :

Set<String> s = new HashSet<>();

, Set . , - , , ClassCastException. , , , ClassCastException , .

+3
source

All Articles