Why declare a variable as a template?

The following things are sometimes written in Java tutorials :

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

Although I understand the benefits of using type parameters and wildcards in class definitions and methods, I am interested in the following:

  • What are the benefits of providing a variable of type containing a wildcard?
  • In real life, people do this, and when?
+4
source share
3 answers

Wildcards are really only useful in method parameter declarations, as they increase the range of valid parameter types, for example:

void original(List<Number> list) { /* ... */ }
void withUpperWildcard(List<? extends Number> list) { /* ... */ }
void withLowerWildcard(List<? super Number> list) { /* ... */ }

original(new ArrayList<Number>());       // OK.
original(new ArrayList<Integer>());      // Compiler-error.
original(new ArrayList<Object>());      // Compiler-error.

withUpperWildcard(new ArrayList<Number>());  // OK.
withUpperWildcard(new ArrayList<Integer>());  // OK.

withLowerWildcard(new ArrayList<Number>());  // OK.
withLowerWildcard(new ArrayList<Object>());  // OK.

(, , ) , , , , :

List<? extends Number> method() { /* ... */ }

// Compiler error.
List<Number> list1 = method();
// OK, but yuk!
List<? extends Number> list2 = method();         
// OK, but the list gets copied.
List<Number> list3 = new ArrayList<Number>(method());  

( , ).

Java 2nd Ed:

, , - API .

+2

. :

Set<?> unknownSet = new HashSet<String>();
System.out.println(unknownSet); // prints empty set: []
unknownSet.add("salala"); // compile error

, Diamond Operator :

Set<String> unknownSet = new HashSet<>();
unknownSet.add("salala"); // okay now
System.out.println(unknownSet); // prints single set: [salala]

, . :

Set<Object> unknownSet = new HashSet<>();
unknownSet.add("salala"); // adding a String
unknownSet.add(42); // adding an Integer
System.out.println(unknownSet); // prints set, sg like this: [42, salala]
+2

.

:

, , Object. , . , List.size List.clear. , , T.

But , when I declare a variable, I agree that this is NOT something more useful, because your variable is already limited to the RHS and infact side, you cannot add elements to it String, as indicated in another answer. An unlimited pattern is more useful in methods such as those printListused in the example mentioned in the link above.

+1
source

Source: https://habr.com/ru/post/1650807/


All Articles