1

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.

2

3 Answers 3

1

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?

Sign up to request clarification or add additional context in comments.

1 Comment

@user2793388: you can accept it as an answer if you deem it worthy as such.
0
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).

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.