user4709932
user4709932

Reputation:

Add specific item from ArrayList into LinkedList Java

I have an ArrayList with lots of objects. I want to be able to add any objects into a choice of 3 different LinkedLists. A user input will select which item to add to which LinkedList by typing the index they wish to be added. This is the kind of thing i'm after, but i just can't get it to work:

public void addToRepository(int indx, int r) {
    if (r == 1){ //checks to see if chosen repository 1
        for (int i=0; i < itemList.size(); i++) {
            i = indx;
        } // ignore this it was just me playing around to see if i'd be able to get the index this way..
        repo1.add(itemList.get(indx)); //adds item from "itemList" with the index that
                                         the user input has given
    //other if statements   
    }                                   
}

I'm not sure this is the correct idea but it gives error "Item cannot be converted to String". If not, how can i go about doing this?

Upvotes: 0

Views: 49

Answers (1)

Aniket Thakur
Aniket Thakur

Reputation: 68935

So you have

ArrayList<Item> itemList = new ArrayList<Item>();

and you are trying to do -

repo1.add(itemList.get(indx)); 

As per the Exception you are getting it looks like repo1 has String data. You can do one of the following things -

  1. Use repo1.add(itemList.get(indx).toString()); OR
  2. Change repo1 generics to include Item data instead of String

Upvotes: 1

Related Questions