错误“main”java.lang.ArrayIndexOutOfBoundsException

时间:2014-01-06 05:20:53

标签: java indexoutofboundsexception

我在线程“main”java.lang.ArrayIndexOutOfBoundsException:错误中遇到异常 Eclipse对我说它是在这个代码声明中

            myArray[i][j] = tmpDouble;

但我不知道为什么。

代码:

public class MyClass {

    private int N;
    private double[][] myArray = new double[N][N];
    private ArrayList<anObject> myList;

    public MyClass(ArrayList<anObject> aList){

        myList = new ArrayList<anObject>();
        myList = aList;

        HashSet<String> uniqueSet = new HashSet<String>();

        String[] anArray = uniqueSet.toArray(new String[uniqueSet.size()]);
        N = uniqueSet.size();
        for (int i=0;i<N;i++){
            for (int ii=0;ii<N;ii++){
                myArray[i][ii] = 0.0;
            }
        }
    }
    for (int i=0;i<N;i++){
            //if (i==j)myArray[i][j]=0;
            for(anObject s : myList){
                if (s.getName1().equals(arrayNameOfHashSet[i])){
                    tmpDouble = Math.abs(s.getScore1()-s.getScore2());
                    tmpString = s.getName2();
                    for (j=0;j<N;j++){
                        if (s.getName2().equals(arrayNameOfHashSet[i])){
                            break;
                        }
                    }
                }   

            myArray[i][j] = tmpDouble;
            }
    }

}

2 个答案:

答案 0 :(得分:1)

您的数组myArray的大小为0。 您需要再次初始化它:

N = uniqueSet.size();
myArray = new double[N][N];

答案 1 :(得分:1)

 HashSet<String> uniqueSet = new HashSet<String>();

   private int N= uniqueSet.size(); // assign some value to N
    private double[][] myArray = new double[N][N];