ArrayList <myclass>发布</myclass>

时间:2013-10-25 13:45:17

标签: java object arraylist

我正在尝试从句子中获取所有可能的单词对,并将其存储到 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;
}}

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

以下是一些代码:

 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

2 个答案:

答案 0 :(得分:4)

class MyClass {

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

删除字段上的static修饰符。

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

read more about it

答案 1 :(得分:0)

删除static修饰符。

来自JLS 8.3.1.1. static Fields

  

如果一个字段被声明为静态,那么它只有一个化身   该字段,无论该类有多少个实例(可能为零)   最终可能会创建。静态字段,有时称为类   变量,在类初始化时体现(第12.4节)。

     

未声明为静态的字段(有时称为非静态字段   field)被称为实例变量。每当一个新的实例   创建了一个类(第12.5节),一个与该实例关联的新变量   为在该类或任何类中声明的每个实例变量创建   它的超类。

有关详细信息,请参阅static Fields

所以将代码更改为,

class MyClass{

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