Ernestas Gruodis
Ernestas Gruodis

Reputation: 8787

"Warning: [unchecked] unchecked cast" when casting Object to ArrayList<String[]>

Strange situation - below is the code:

ArrayList<String[]> listArr = new ArrayList<>();
Object[] obj = new Object[]{"str", listArr};

String str = (String) obj[0];//OK
ArrayList<String[]> list = (ArrayList<String[]>) obj[1];//warning: [unchecked] unchecked cast

When project is built (with compiler option -Xlint:unchecked in project properties), I get one warning:

warning: [unchecked] unchecked cast
ArrayList list = (ArrayList) obj[1];
required: ArrayList
found: Object

But casting String in the same way is OK. What is the problem here?

Upvotes: 7

Views: 2441

Answers (3)

shikjohari
shikjohari

Reputation: 2288

This is because the compiler can not verify the internal types at the list level, so you need to first verify for list. And the internal types individually.

Instead of ArrayList<String[]> list = (ArrayList<String[]>) obj[1];

It should be ArrayList<?> list = (ArrayList<?>) obj[1];

Upvotes: 6

Ben Win
Ben Win

Reputation: 840

The compiler complains

ArrayList<String[]> list = (ArrayList<String[]>) obj[1]

because a cast is a runtime check. So at runtime your ArrayList<String[]> could be a ArrayList<Whatever[]>, because the type of obj is unknown.

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

This is because if you try to cast Integer to String you will get ClassCastException at runtime. But there will be no ClassCastException here:

    ArrayList<Integer[]> listArr = new ArrayList<>();
    ArrayList<String[]> list = (ArrayList<String[]>) obj[1];

Upvotes: 2

Related Questions