I am facing a very simple issue :
List<String> myList = new Vector<String>(10);
myList.add(5,"HELLO");
gives me ArrayOutOfBoundException : 5>0
Is there a way to specify the size of a Vector and fill the list in random order?
You're not specifying the size, you're specifying the capacity of Vector
. You could do:
List<String> myList = new Vector<String>();
for(int i = 0;i < 10; i++)
myList.add(null);
myList.set(5, "HELLO");
What you should do is forget the Vector
class, since it's been outdated for over 10 years already.
If you just need fixed size and random access, you can use an array
String[] myArr = new String[10];
If you need it to be a Collection
, you can use
List<String> myList = Arrays.asList(myArr);
Finally if you want to add more elements in it ( Arrays.asList()
returns a fixed size list) you can use
List<String> myList = new ArrayList<>(Arrays.asList(myArr));
The documentation of the add()
method explicitly states:
ArrayIndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
Since your size at the moment is 0, the behaviour is as expected. The constructor of the Vector
class specifies the initial capacity, not the size of the collection.
After checking out what was said in the comments, I am removing my suggestion. It's better to stick to arrays in that case.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.