【问题标题】:Add ArrayList to another ArrayList in java with Iterator使用 Iterator 将 ArrayList 添加到 java 中的另一个 ArrayList
【发布时间】:2014-11-25 00:02:24
【问题描述】:

我的代码有一个大问题:

public class BookStore
{
    private ArrayList<Book> books;
}



/**
* This method takes the author's name as a String parameter and returns an
* arraylist of all the books written by that author. It uses a while loop
* and an iterator, locates the books written by that author (case-insensitive)
* and adds them to another arraylist. 
*/
public ArrayList<Book> getBooksByAuthor(String authorName){             
    ArrayList<Book> getBooksByAuthor =  new ArrayList<Book>();
    Iterator<Book> aBook = books.iterator();  
    while(aBook.hasNext()){
        Book aBookd = aBook.next();
        if (authorName.equalsIgnoreCase(aBookd.getAuthor())){  
            books.add(getAuthor());     
            books.addAll(getBooksByAuthor);
        }   
    } 
    return getBooksByAuthor.size();
}

那三行

  • books.add(getAuthor());
  • books.addAll(getBooksByAuthor);
  • return getBooksByAuthor.size();

我很确定他们完全错了。我尝试了不同的方法来做到这一点,但没有奏效。我真的不明白该怎么做。有人可以帮助我吗?感谢您的宝贵时间!

【问题讨论】:

  • 你试过运行这段代码吗?它从一个类开始,该类只定义了一个外部无法访问的数组列表,没有任何方法来操作该列表,以及一个与该类完全分离的函数。实际调用此函数并执行某些操作的其余代码在哪里?
  • 看起来你只想用getBooksByAuthor.add(aBookd); 代替你提到的前两行。而且这段代码不会按原样编译——getBooksByAuthor.size(); 是一个int,你必须返回一个ArrayList&lt;Book&gt;——大概是getBooksByAuthor。无关紧要,你的命名很糟糕。

标签: java arraylist


【解决方案1】:

我相当确定您想将具有匹配作者姓名的书籍添加到新列表中。使用for-each loop的隐式迭代器

List<Book> al = new ArrayList<>();
for (Book book : books) {
    if (authorName.equalsIgnoreCase(book.getAuthor())) {  
        al.add(book);     
    }   
} 
return al;

或使用明确的Iterator 类似

List<Book> al = new ArrayList<>();
Iterator<Book> iter = books.iterator();
while (iter.hasNext()) {
    Book book = iter.next();
    if (authorName.equalsIgnoreCase(book.getAuthor())) {
        al.add(book);
    }
}
return al;

【讨论】:

  • 它有效!感谢您的宝贵时间。
【解决方案2】:

是否需要迭代器和 while 循环而不是 foreach 循环?

你想要达到的(我认为)普通语言是:我们有一个空的集合/列表作为结果。对于书籍列表中的每本书,检查作者是否与给定名称具有相同的名称 - 如果名称相同,我们将这本书添加到生成的集合/列表中。

代码如下:

public ArrayList<String> getBooksByAuthor(String authorName) {
    ArrayList<Book> result = new ArrayList<Book>();
    for (Book aBook : books) { //[for each notation in java ][1]
        if (authorName.equals(aBook.getAuthor())) {
            result.add(aBook);
        }
    }
    return result;
}

如果您想使用 while 循环,请阅读 this link 中的 foreach/while 循环转换。

此外,正如 cmets 中所述,您的代码存在一些语义和句法错误:

  • 您的返回类型错误(int 而不是 ArrayList)
  • 你的类定义右括号在你的方法定义之前结束
  • 您将作者对象(可能是一个字符串)添加到您的书籍收藏中
  • 您永远不会将任何书籍添加到您的结果收藏中
  • 您尝试将 addAll(空)集合 getBooksByAuthor 的对象添加到您的书籍中,而不是将一些/单本书添加到您的 getBooksByAuthor 集合中

    [1]http://docs.oracle.com/javase/1.5.0/docs/guide/language/foreach.html

【讨论】:

  • 非常感谢!我会看看你的链接。
猜你喜欢
  • 2013-05-19
  • 1970-01-01
  • 1970-01-01
  • 2017-01-11
  • 2018-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多