Reputation: 11
Let's say I have a class called myClass<K,V>
.
In my class I have an ArrayList
called myArrayList
.
How would I go about placing something of type V
into a certain spot in the array list.
For example, trying something like myArrayList[place] = vThing
doesn't seem to work.
Here's the declaration:public ArrayList<V> myArrayList[];
. I added myArrayList.add(place, value);
, but I'm getting an error that says "cannot invoke add(int, V) on the array type ArrayList[]".
I get it now, I was thinking that an arraylist would work like an array, but it appears as though is works more like a list.
Upvotes: 1
Views: 391
Reputation: 327
I would advice to learn searching in http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html (for example) you can find there all available methods.
For example :
void add(int index, E element)
Inserts the specified element at the specified position in this list.
Upvotes: 0
Reputation: 44439
An ArrayList
has an overload for the add()
method
add(int index, E element)
for this exact purpose. You cannot access it using square brackets like an array.
Adding a generic type has nothing to do with this (assuming you define your ArrayList
as List<V> myArrayList = new ArrayList<>()
).
Responding to your edit. Change
public ArrayList<V> myArrayList[]
to
public ArrayList<V> myArrayList
If you put square brackets there, it will consider it.. Hell, I'm not even sure. It's just bad practice. I'm guessing an array of arraylists? Or an arraylist of arrays?
Upvotes: 1
Reputation: 1315
add(int index, E element)
Inserts the specified element at the specified position in list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
Upvotes: 0