Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Vector Collection

 
Shiva Mohan
Ranch Hand
Posts: 486
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Folks,
Here is my doubt in Vector Collection.




Line 1 I used, List instanceof Vector.I thought Collection instanceof Vector would work the same way.

When I try to change Collection instanceof Vector,the method (line 2) (theSet.add(0,�Chicago�) showing compilation error.Why?

Question no 2 o I need to give the index order properly(0,1,2).When I tried to change the order,it gave me ArrayIndexOutOfBoundsException.

Please someone clarify those doubts for me.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the Collection interface, there is only one add method. This takes a single argument (the Element being added).

Collection is a superinterface of the List interface. In List, the interface is expanded to include an overloaded version of the add method. This takes two arguments (an int index, along with the Element being added).

By upcasting to the Collection type, the overloaded version of add (in List) becomes unavailable, and generates the compiler error.

Note that the add(int index, E element) method in List throws an IndexOutOfBoundsException if index > size(), where size() returns "the number of elements in this list." (As implemented in Vector, this method throws an ArrayIndexOutOfBoundsException, which extends IndexOutOfBoundsException.)
[ March 16, 2006: Message edited by: marc weber ]
 
ak pillai
author
Ranch Hand
Posts: 288
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stay away from Vector and try to use an ArrayList.

List list = new ArrayList(20);

If you need threadsafety, try and use


List list = Collections.synchronizedList(new ArrayList(20));

or if you are using JDK1.5 look at java.util.concurrent package
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic