Use of wildcards in java generics -


i attempting understand java generic wildcards.i came across basic program.it appears me thing can added list s "null". cannot add example

s.add(new integer (4));   or  s.add(new char(a)); 

before reading lot of material , confusing mind,i attempting understand java designers going introducing wildcards in generics.from point of view cannot see useful feature coming generic wildcards.it possible appears due lack of experience , since new java.it if people share thoughts on matter.

import java.util.linkedlist; import java.util.iterator;  public class wildcardexampleone {      public static void main(string[] args)     {         linkedlist<?> s = new linkedlist<integer>();         s.add(null);          iterator<?> x = s.iterator();          object o = x.next();          system.out.println(o);          /* note linkedlist<?> not same type linkedlist<object>          * here statements wouldn't compile:          */         // s.add(new integer(3));          // iterator<object> x = s.iterator();     } } 

it appears me thing can added list s "null".

yes, correct. however, receive list don't need (and aren't supposed to) add elements to. example, consider simple method prints list's elements standard output, 1 per line:

public static void printall(final list<?> list) {     (final object elem : list) {         system.out.println(elem);     } } 

this method doesn't need know list's element-type is; can called on list<string>, arraylist<integer>, linkedlist<object>, or other list<?>.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -