提问者:小点点

HashSet在添加到对象后更改其值


我试图向ArrayList对象添加构造函数有3个参数(int,int,hashset)的对象。当我添加一个新对象时,哈希集中的值会发生某种变化,所以我添加了错误的值。例如,我创建3个对象,添加这3组整数:

142082 74016 122517 57432 97112  
142082 150224 112373 129671 57432 97112 138427 115659 102283 147774  
142082 31491 129671 855 57432 73545 123160 124682 147774 61966 58590 

但object会收到这些:

70213 131022 118104 137949 4003 13798 23598 129525  
70213 131022 118104 137949 4003 13798 23598 129525  
70213 131022 118104 137949 4003 13798 23598 129525 

我不明白为什么集合会改变其值。这是函数代码:

//Array of ParagData objects
public static ArrayList<ParagData> getAllParagsDatas(String indexed_data_tab) throws SQLException{
    ArrayList<IndexedItem> allIndexedItems = new ArrayList<>();
    ArrayList<ParagData> allParags = new ArrayList<>();
    HashSet<Integer> wordsId = new HashSet<>();
    //Array of all indexed words
    allIndexedItems = GuiFindFrags.myConnection.getAllIndexedItems(indexed_data_tab);

    int curCycledParag = 1; //current paragraph num
    int curCycledTextId = 1; //current text id

    for(int i = 0; i < allIndexedItems.size(); i++){
        if((allIndexedItems.get(i).textId == curCycledTextId) && allIndexedItems.get(i).paragNum == curCycledParag){
            if(allIndexedItems.get(i).wordId != 0) wordsId.add(allIndexedItems.get(i).wordId);
        }
        else {          
            allParags.add(new ParagData(allIndexedItems.get(i).textId, allIndexedItems.get(i).paragNum, wordsId));
            wordsId.clear();
            curCycledParag = allIndexedItems.get(i).paragNum;
            curCycledTextId = allIndexedItems.get(i).textId;
        }
    } 
    return allParags;
}

在这段代码中我:

allIndexedItems = GuiFindFrags.myConnection.getAllIndexedItems(indexed_data_tab);

>

  • 获取对象的ArrayListallIndexedItems,描述文本中的单词(文本在mysql表中)。此对象具有以下参数:

      < li>int text_id(在哪个文本中找到该单词) < li>int parag_num(在文本的哪个段落中找到) < li>int word id -(词典中单词的id,也在mysql表中)

    此对象的构造函数中还有其他参数,但这里没有使用它们。这个数组列表描述了所有文本中的所有单词。

    int curCycledParag = 1; //current paragraph num
    int curCycledTextId = 1; //current text id
    

    为当前文本和当前段落创建变量。它们将在周期中更改。

    同样在开始的时候,我创建了< code>HashSet

    SO:当段落的所有单词都添加到 HashSet 时,我必须创建另一个对象,描述段落 - 对象 ParagData(它具有:

      < li>int text_id(此段落所在文本的id) < li>int parag_num(文本中的段落数) < li>HashSet wordIdsSet -(段落的所有单词id)

    一开始我还创建了一个ArrayList

    else {              
        allParags.add(new ParagData(allIndexedItems.get(i).textId, allIndexedItems.get(i).paragNum, wordsId));
        wordsId.clear();
        curCycledParag = allIndexedItems.get(i).paragNum;
        curCycledTextId = allIndexedItems.get(i).textId;
    }
    return allParags;
    

    当我向数组列表添加新的ParagData对象时,它的值会改变——所以不正确的值会被添加到所有parag的数组列表中


  • 共1个答案

    匿名用户

    为每个段落创建一个新的Hashset对象。Hashset在创建后不是不可变的。你面对的是同一个物体。