top of page

Set vs. Set<?>

  • taolius
  • Jun 21, 2019
  • 1 min read

https://www.programcreek.com/2013/12/raw-type-set-vs-unbounded-wildcard-set/

There are two facts about Set<?>: Item 1: Since the question mark ? stands for any type. Set<?> is capable of holding any type of elements. Item 2: Because we don't know the type of ?, we can't put any element into Set<?>

So Set<?> is mainly to used as a method parameter, to let user know that this method can take any kind of Set input.

<pre><code>

//Legal Code

public static void main(String[] args) {

HashSet<Integer> s1 = new HashSet<Integer>(Arrays.asList(1, 2, 3));

printSet(s1);

HashSet<String> s2 = new HashSet<String>(Arrays.asList("a", "b", "c"));

printSet(s2);

}

public static void printSet(Set<?> s) {

for (Object o : s) {

System.out.println(o);

}

}

</pre></code>

 
 
 

Comments


© 2023 by BI World. Proudly created with Wix.com

  • Facebook Basic Black
  • Twitter Basic Black
  • YouTube Basic Black
bottom of page