java - 将 ArrayList 中的特定项添加到 LinkedList Java

标签 java arraylist

我有一个包含很多对象的ArrayList。我希望能够将任何对象添加到 3 个不同的 LinkedLists 中。用户输入将通过键入要添加的索引来选择将哪个项目添加到哪个 LinkedList。这就是我想要的东西,但我就是无法让它发挥作用:

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   
    }                                   
}

我不确定这是正确的想法,但它给出了错误“项目无法转换为字符串”。如果没有,我该如何去做呢?

最佳答案

所以你有

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

而你正在尝试做 -

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

根据您收到的异常,它看起来像 repo1 有字符串数据。您可以执行以下操作之一 -

  1. 使用repo1.add(itemList.get(indx).toString());
  2. 更改 repo1 泛型以包含 Item 数据而不是 String

关于java - 将 ArrayList 中的特定项添加到 LinkedList Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29271253/

相关文章:

java - 使用嵌套的 While 语句迭代两个 ArrayList - Java

java - AWS Elastic Beanstalk 环境变量编码和字符集

java - 将 Long[] 转换为 long[](原始)java

java - 如何将 float 部分调整为下一个整数值

java - 用新的字符串值替换 ArrayList 值

java - 用arraylist创建对象并清除,但不清除对象中的arraylist

java - 每个声明之间有什么区别,对每个声明有什么影响?

java - 在 Java 中读取文件、替换单词并写入新文件

Java ArrayList<GenericObject>.remove(GenericObject) 返回 false,但仍减少 ArrayList 的大小

java - 将 Object[] 转换为 int[] 错误