I am solving a problem on spoj, here is the URL http://www.spoj.com/problems/FACEFRND/
But getting an error and unable to identify my mistake, code is as follows:
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());
}
}
Error is with sample input:
3
2334 5 1256 4323 7687 3244 5678
1256 2 2334 7687
4323 5 2334 5678 6547 9766 9543Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1256, Size: 5
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.remove(ArrayList.java:474)
at sampleproject.Facefrnd.main(Facefrnd.java:22)
The Arraylist.remove()
method for ArrayLists
of type Integer
defaults to the remove that takes an index. In order to remove it, you can do:
fof.remove(new Integer(id));
This ensures that the remove(Object o)
method is called instead.
Sample Code:
ArrayList<Integer> test = new ArrayList<Integer>();
test.add(123);
test.remove(new Integer(123));
System.out.println(test.size());
This will print "0".