-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 回答