0

I have a databean that holds a List. This is set using the data returned from a generic list. But while I try to iterate over the list I get a class cast exception. Below is the structure,

class DataBean {
  List<Integer> data;
  //getter and setter
}

class DataSetter {
  public <E> List<E> operate() {     
    List <E> returnList = new ArrayList<E>();
    //Compute
    return returnList;
  }
}

class Main {
  main() {
    List<Integer> current = dataSetter.operate();
    dataBean.setM(current); //works as expected

    List <Integer> temp = dataBean.getM();//works as expected
    System.out.println(temp);//prints as expected

    for(int i : temp) {  //exception java.lang.String cannot be cast to java.lang.Integer
      System.out.println(i);
    }
  }
}

Why do I see such an exception? If the list that is returned is not an Integer list should it generate an exception when it tries to set it to the class variable? How can the class variable be set and returned properly if there is a type mismatch and why do I see this only when I try to iterate over the list?

1 Answer 1

0

If the list that is returned is not an Integer list should it generate an exception

Actually, no.

In Java, generics use type erasure. That means that the type checking of generics is done at compilation time, but not at runtime. At runtime, there is no difference between List<Object> or List<String>. In fact, they are all equal to the old, unparametrized List.

So, you can do something like

List<String> myList1 = new ArrayList<String>();
myList1.add("HELLO");
List myList2 = myList1;
List<Integer> myList3 = (List<Integer>) myList2;

and all you get is a warning at compile time (and the warning is because it cannot ensure that the cast is really valid, and you won't get a ClassCastException at runtime).

1
  • Thx. That helped. I wanted to create a wrapper that would be able to return me a generic list which I can later cast to the type I want. I guess I'll figure out a workaround or do something else instead.
    – Manoj
    Feb 25, 2015 at 11:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.