-2

I was using the following code to create a generic array of lists to mix up different types of lists:

List<Integer>[] intLists = (List<Integer>[])new List[] {Arrays.asList(1)}; 
List<? extends Object>[] objectList = intLists;
objectList[0] = Arrays.asList(1.01);
int n = objectList[0].get(0); // class cast exception!

But it gave me a cast exception. How can I work around this?

mahi
  • 35
  • 4

3 Answers3

1

I am not sure if this gives a compile error though it apparently is creating a raw array of lists and while storing it seems the compiler cannot detect that its an array of List (it cannot detect the type of list - so perhaps it just interprets it as a raw list) and hence does not throw an error and when you try and retrieve the element into an integer it fails while trying to cast a double into an int. This is not a correct usage.

I believe you can do (Integer) listArray[0].get(0) but it will cause precision loss post the floating point.

Ulysses
  • 5,616
  • 7
  • 48
  • 84
0

The type of objectList[0].get(0); is Double so you have to convert it to an int. The following works:

int n = ((Double) objectList[0].get(0)).intValue();

But depending on you use case you code is not very good.

mohe2015
  • 61
  • 2
  • 6
0

You're trying to store a double value in an integer variable. You can't do that. So just store it in a double instead:

        List<Integer>[] intLists = (List<Integer>[])new List[] {Arrays.asList(1)}; 
        List<? extends Object>[] objectList = intLists;
        objectList[0] = Arrays.asList(1.01);
        double n = (double) objectList[0].get(0); // Make it a double :)
Eren
  • 68
  • 3
  • 9