How to fix: java.lang.ClassCastException: java.util.ArrayList cannot be passed to java.lang.Integer

I got 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 cannot make Paretoset an integer arraylist as it creates problem in other parts of my program. I met an exception on the line toPass.add ((Integer) paretoSet.get (i));
like java.lang.ClassCastException: java.util.ArrayList cannot be cast to java.lang.Integer How can I fix this problem?
thanks in advance

+3


source to share


2 answers


If ParetoSet

is a collection of ArrayList

, then the call ParetoSet.get(i)

will return ArrayList

to the index i

. As the error says, ArrayList

it is not a type Integer

and cannot be passed to one.

Other attractions:

  • Your variable should be a camel case: ParetoSet

  • auto-boxing means that casting into a for loop was unnecessary since JDK5
  • ParetoSet

    was declared with a raw type
  • makes type inference new ArrayList<Integer>()

    redundant since JDK7

EDIT

  • Your variable should be a camel case: ParetoSet

    as per Jim's comments


EDIT

ArrayList is not conceptually or actually whole. If you say that the sentence "List is an integer type" does not 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

      

Thus, we can say, for example, what ArrayList

is a type AbstractList

or AbstractCollection

, but not Integer

because Integer

it is not part of its line.

+2


source


your program has a type problem on the lines below. you are trying to add a list of types arrayalist to Integer arryalist. it is not right. if you want to add arraylist objects to another arraylist. Please use generics as an object.

ArrayList ParetoSet=new ArrayList();   // contains a collection of ArrayList
toPass.add((Integer)ParetoSet.get(i));

      

It should look like this:



ArrayList<ArrayList> ParetoSet=new ArrayList<ArrayList>();  
ArrayList<ArrayList> toPass=new ArrayList<ArrayList>();  
toPass.add(ParetoSet.get(i));

      

Then you need to change a bit of code to match your logic

0


source







All Articles