简体   繁体   中英

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?

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM