-1

spoj で問題を解決しています。URL はhttp://www.spoj.com/problems/FACEFRND/です。

しかし、エラーが発生し、私の間違いを特定できません。コードは次のとおりです。

import java.util.ArrayList;
import java.util.Scanner;

public class Facefrnd {

    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        ArrayList<Integer> f = new ArrayList<Integer>();
        ArrayList<Integer> fof = new ArrayList<Integer>();
        int n, t, id, m;
        n = sc.nextInt();
        t = n;
        while(t>0){
            t--;
            id = sc.nextInt();
            m = sc.nextInt();
            f.add(id);
            if(fof.contains(id))
                fof.remove(id);
            for(int j = 0; j < m; j++){
                id = sc.nextInt();
                if(!f.contains(id))
                    fof.add(id);
            }
        }
        System.out.print(fof.size());
    }

}

エラーはサンプル入力にあります:

3

2334 5 1256 4323 7687 3244 5678

1256 2 2334 7687

4323 5 2334 5678 6547 9766 9543スレッド「メイン」で例外 java.lang.IndexOutOfBoundsException: インデックス: 1256、サイズ: 5

java.util.ArrayList.rangeCheck(ArrayList.java:635) で

java.util.ArrayList.remove(ArrayList.java:474) で

sampleproject.Facefrnd.main(Facefrnd.java:22) で

4

1 に答える 1

1

タイプのArraylist.remove()メソッドのデフォルトは、 indexを取る remove です。それを削除するには、次のようにします。ArrayListsInteger

fof.remove(new Integer(id));

これにより、remove(Object o)メソッドが代わりに呼び出されることが保証されます。

サンプルコード:

ArrayList<Integer> test = new ArrayList<Integer>();                          
test.add(123);                                                               
test.remove(new Integer(123));                                               
System.out.println(test.size());   

これにより、「0」が出力されます。

于 2014-10-06T19:20:33.473 に答える