Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array cast Java 8 vs Java 9

Does anyone have insights on why this code works on java 8 but not on java 9

String[] strings = (String[]) Arrays.asList("foo", "bar").toArray();
for (String string : strings) {
    System.out.println(string);
}

I understand we can specify the type while doing toArray instead of casting it. But I found this issue while debugging one of our dependency (hive-metastore-2.1.1 HiveMetaStoreClient line 274). So I don't have the liberty to change the code and we are running java 9. Is there a way to get around this? Is this a problem with java 9(since it seems like a breaking change) or just file a bug in the hive repo.

like image 771
Vishnu Avatar asked Jul 17 '18 03:07

Vishnu


People also ask

Can you type cast arrays in Java?

you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted. You can make an array of Integer, and after that copy every value of the first array into second array.

Can we convert array to list in Java?

We can convert an array to arraylist using following ways. Using Arrays. asList() method - Pass the required array to this method and get a List object and pass it as a parameter to the constructor of the ArrayList class. Collections.

What method is used to convert from an array to a list?

asList() Method. In this method, the Array is passed as the parameter into the List constructor with the help of the Arrays. asList() method.


1 Answers

Seems like it might be due to the change (coll) Arrays.asList(x).toArray().getClass() should be Object[].class

Looks like they fixed a bug that toArray could return types other than Object.

Quoting the release notes

This may cause code that was expecting the old behavior to fail with a ClassCastException...If this problem occurs, rewrite the code to use the one-arg form toArray(T[]), and provide an instance of the desired array type. This will also eliminate the need for a cast.

So it seems like you'll need to file a bug in the Hive repo to update the code to work after this change.

Looks like they actually added a configuration value in a future commit which if set with a certain value would actually avoid the code path causing the issue. https://github.com/apache/hive/commit/07492e0d2f1942c1794a3190610e10207c850cf7#diff-ca39aa4869cc58909a31c761cd7a27ccR257

Maybe you can upgrade to a version that has this and use this configuration to avoid the problem. So long as you don't care about the functionality that requires that code path. Seems like the code causing the problem is selecting which URI to use randomly instead of just picking the first one out of a list.

like image 187
JakeM Avatar answered Nov 08 '22 16:11

JakeM