gpt4 book ai didi

java - ArrayList 问题

转载 作者:行者123 更新时间:2023-12-01 18:42:01 25 4
gpt4 key购买 nike

我正在尝试从句子中获取所有可能的单词对并将其存储到 ArrayList
其中MyClass.java

class MyClass{

private static ArrayList<String> wordList;
private static ArrayList<Integer> wordListCode;
private static int frequency;
private static int timeId;

public MyClass(ArrayList<String> words, int tid, int freq){
wordList = new ArrayList<String>();
wordListCode = new ArrayList<Integer>();

if(words.get(0).hashCode()> words.get(1).hashCode()){
wordList.add(words.get(0)); wordListCode.add(words.get(0).hashCode());
wordList.add(words.get(1)); wordListCode.add(words.get(1).hashCode());
}else{
wordList.add(words.get(1)); wordListCode.add(words.get(1).hashCode());
wordList.add(words.get(0)); wordListCode.add(words.get(0).hashCode());
}
frequency = freq;
timeId = tid;
}}

我的问题是,当我尝试向 ArrayList 添加一个 MyClass 对象时,添加了一个节点,但替换了所有其他节点节点具有最后一个节点的值...

这是一些代码:

 ArrayList<MyClass> couples = new ArrayList<MyClass>();
ArrayList<String[]> couplesList = new ArrayList<String[]>();
couplesList = getWordCouplesList("demanding forensic technical comms systems");
for(int o=0; o<couplesList.size(); o++){
String word1, word2;
if(couplesList.get(o)[0].hashCode()> couplesList.get(o)[1].hashCode() ){
word1 = couplesList.get(o)[0];
word2 = couplesList.get(o)[1];
}else{
word1 = couplesList.get(o)[1];
word2 = couplesList.get(o)[0];
}
ArrayList<String> items = new ArrayList<String>(Arrays.asList(couplesList.get(o)));
MyClass temp = new MyClass((ArrayList)items, 1, 1);
couples.add( temp);
}

for(int i=0; i<couples.size(); i++){
System.out.println((i+1)+"couple = "+couples.get(i).getWordList().get(0)+" , "+couples.get(i).getWordList().get(1));
}
<小时/>

这给出了输出:

1couple = comms , systems
2couple = comms , systems
3couple = comms , systems
4couple = comms , systems
5couple = comms , systems
6couple = comms , systems
7couple = comms , systems
8couple = comms , systems
9couple = comms , systems
10couple = comms , systems

最佳答案

class MyClass {

private ArrayList<String> wordList;
private ArrayList<Integer> wordListCode;
private int frequency;
private int timeId;
...
.....
}

删除字段上的static修饰符。

这意味着您为该 MyClass 的每个对象使用相同的实例,这是您不想要的。您希望每个实例都有自己的列表和属性。

read more about it

关于java - ArrayList<MyClass> 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19591580/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com