0

I'm trying to get all possible word couples from a sentence and store it to an ArrayList
where 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;
}}

My problem is that when I'm trying to add an MyClass object to the ArrayList, adds one node but replaces all the other nodes with the values of the last one...

Here is some code:

 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));
    }  

This gives output :

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
4

2 回答 2

4
class MyClass {

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

删除static字段上的修饰符。

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

阅读更多关于它的信息

于 2013-10-25T13:53:22.857 回答
0

删除static修饰符。

JLS 8.3.1.1. static Fields

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

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

有关更多信息,请参阅 静态字段

因此,将您的代码更改为,

class MyClass{

  private ArrayList<String> wordList;
  private ArrayList<Integer> wordListCode;
  private int frequency;
  private int timeId;
  ...
  .....
}}
于 2013-10-25T13:53:37.670 回答