• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics adding to List (? extends Object)  RSS feed

 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
K&B state that List(? extends Object) can be accessed but but not modified.

Well take a look at this code.

import java.util.*;

class Test
{
public static void main ( String args [ ] )
{

Object[] ob = {"Dog", "Cat"};

List<? extends Object> lis = new ArrayList( Arrays.asList(ob));

System.out.println(lis);

lis.add(null);
System.out.println(lis);
}
}

The output is
[Dog, Cat]
[Dog, Cat, null]

As you can see lis has been modified, contrary to K&B.
 
victor kamat
Ranch Hand
Posts: 247
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
K&B state that List(? extends Object) can be accessed but but not modified.
Page 610
 
Manju Devarla
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try out this program there is compiler error


class Test {
public static void main(String s[]) {
List<Object> lis=new ArrayList<Object>();
addStrings(lis);
for(Object obj:lis)
System.out.println(lis);
}
public static void addStrings(List<? extends Object> list) {
list.add("foo");
list.add("bar");
}
}
 
Priya Viswam
Ranch Hand
Posts: 81
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot add anything into a type declared with ? extends wildcard�but you can add the value null, which belongs to every reference type.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!