• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

asList() doubt

 
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Integer i={3,5}
List l=Arrays.asList(i);
l.set(1,9);

asList method returns list,but list is a interface then how can we invoke a method set on it.

and why we cannot invoke add method on the same list,and if we use add method it compiles well but with some warnings and then it fails at runtime.

please explain.
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Saran,


Integer i={3,5}
List l=Arrays.asList(i);
l.set(1,9);

asList method returns list,but list is a interface then how can we invoke a method set on it.



Think about the line:
List<String> alist = new ArrayList<String>();
alist.add("Hello");
alist.add("howdy");
alist.add("hi");
alist.set(1,"rowdy"); // Can we do this? Absolutely you can


Now your question:
When you are using set(), it is not going to add a new object to the list,
it is just modification, but add() will add a new object so this is not allowed. What asList() returns is fixed List.

java.lang.UnSupportedOperationException is thrown at run time when you apply
add() method to it.

Note: What warning you are getting is not due to the add() method.
Actually your List reference "l" is raw type. It should be parameterized
as :
List<Integer> l1;

Regards,
cmbhatt
[ April 11, 2007: Message edited by: Chandra Bhatt ]
 
sharan vasandani
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
ok,

but list is a interface how does it have a method set then?
thnks
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
List is an Interface and has set() method but it is defined by concrete classes as ArrayList.

Your doubt will disappear when you see the output of the following code:



Any Doubt???

Saran, I liked your question!!! Keep it up!

Regards,
cmbhatt
[ April 11, 2007: Message edited by: Chandra Bhatt ]
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic