有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java将对象添加到arraylist,除非它已经存在

我应该通读一个文件,将所有新词添加到arraylist中,如果该词已经在列表中,则增加一个计数器,显示它出现的次数。我很好地读入了单词,但是当要将它们添加到列表中时,它似乎忽略了检查单词是否已经在列表中并添加同一单词的倍数的部分。我得到的是:

阅读方法:

public void read(String text) throws Exception{
  File fileText = new File(text);
  Scanner in = new Scanner(fileText);
  while(in.hasNextLine()){
    newWord = new Word(in.nextLine());
    add(newWord.text);
    }
  }

添加到arraylist的方法

public void add(String text){
  for(Word o: wordList){
    if(wordList.contains(newWord.text){
      newWord.increaseCount();
    }else{
      wordList.add(newWord);  
     }
   }

我真的很感谢你的帮助,我完全不知道问题在哪里


共 (3) 个答案

  1. # 1 楼答案

    newWord似乎是你的一个自定义类的实例。你的单词列表应该是一个字符串列表,而不是这个类型,因为你要检查文本(我假设是一个字符串)。这就是为什么每个对象都会被添加到列表中,因为您会用新词文本对照实例地址进行检查。所以改变词表。添加(新词);到词表。添加(newWord.text)

  2. # 2 楼答案

    在使用for each循环遍历列表时,不能从结构上修改列表

    在文件中说明——

    A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

    看这个-

    In Java, can you modify a List while iterating through it?

  3. # 3 楼答案

    我猜,因为你没有为你的Word类包含代码

    下面是应该如何编写add方法。你要么加入计数,要么加入一个新词。我还假设单词的大小写无关紧要

    public void add(String text){
        for (Word o: wordList) {
            if (o.getWord().equalsIgnoreCase(text) {
                o.increaseCount();
                return;
            }   
        }
        wordList.add(new Word(text.toLowerCase());
    }
    

    read方法只调用add方法

    public void read(String text) throws Exception{
       File fileText = new File(text);
       Scanner in = new Scanner(fileText);
       while (in.hasNextLine()) {
           add(in.nextLine().trim());
       }
       in.close();
    }