Reputation: 43
I encountered a problem when I tried to run the following code:
ArrayList paretoSet=new ArrayList(); // contains a collection of ArrayList
ArrayList<Integer> toPass=new ArrayList<Integer>();
int[] fParetoSet=new int[ParetoSet.size()];
int[] gParetoSet=new int[ParetoSet.size()];
for (int i=0;i<paretoSet.size();i++){
toPass.clear();
toPass.add((Integer)paretoSet.get(i));
int [] totake=calculate(toPass);
fParetoSet[i]=totake[0];
gParetoSet[i]=totake[1];
}
`
where claculate(ArrayList x) is a method that takes an integer arraylist and returns an integer array. I can not make Paretoset an integer arraylist as it creates problem in other parts of my program. I encountered an exception in the line toPass.add((Integer)paretoSet.get(i));
as java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.Integer
How should I fix this problem?
Thanks in advance
Upvotes: 3
Views: 60945
Reputation: 1942
If ParetoSet
is a collection of ArrayList
, then the call ParetoSet.get(i)
will return the ArrayList
at index i
. As the error says, an ArrayList
is not a a type of Integer
and cannot be cast to one.
Other points of interest:
pareToSet
Paretoset
has been declared with a raw typenew ArrayList<Integer>()
redundant since JDK7EDIT
paretoSet
, as per Jim's commentsEDIT
An ArrayList is neither conceptually, or actually an Integer. If you say the sentence 'A list is a type of integer' it doesn't make sense. If we check the javadoc for ArrayList we can see that its inheritance tree is:
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.ArrayList<E>
All Implemented Interfaces:
Serializable, Cloneable, Iterable<E>, Collection<E>, List<E>, RandomAccess
So we can say for example that ArrayList
is a type of AbstractList
, or AbstractCollection
, but not an Integer
as Integer
is not part of its lineage.
Upvotes: 2
Reputation: 495
your program having typecasting issue on below lines. your are trying to add typecast list of arraylist to Integer arryalist. this wrong. if you want add the arraylist objects to some other arryalist. Please use generics as object.
ArrayList ParetoSet=new ArrayList(); // contains a collection of ArrayList
toPass.add((Integer)ParetoSet.get(i));
This should be like below:
ArrayList<ArrayList> ParetoSet=new ArrayList<ArrayList>();
ArrayList<ArrayList> toPass=new ArrayList<ArrayList>();
toPass.add(ParetoSet.get(i));
Then you should change code bit to fit your further your logics
Upvotes: 0