Imagine we have an array of ints and we want to convert it to a List. Here is the sample:
int[] array = new int[]{42, 5, 1, 3, 4};
List<Integer> list = new ArrayList(Arrays.asList(array));
System.out.println(list.get(0));
What do you think will be printed? That's right, something like
[I@2ff4acd0
It does not look like 42 at all. So, what's the problem?
First of all, let's look at the warnings IDE shows:
Raw use of parameterized class 'ArrayList'
Call to 'asList()' with only one argument
Okay, so let's fix the first one by adding diamond operator <> to new ArrayList:
int[] array = new int[]{42, 5, 1, 3, 4};
List<Integer> list = new ArrayList<>(Arrays.asList(array));
System.out.println(list.get(0));
And now we have a compilation error on the ArrayList creation:
Required type: List<Integer>
Provided: ArrayList<int[]>
It looks like it matches the second warning we saw earlier. The reason is that Arrays.asList(array) does not box int to Integer and creates a List of <int[]>, not a List of Integer as we wanted it to.
There are several ways to fix it:
- The type of
arraycan be changed fromint[]toInteger[]:
Integer[] array = new Integer[]{42, 5, 1, 3, 4};
List<Integer> list = new ArrayList<>(Arrays.asList(array));
System.out.println(list.get(0));
-
arraycan be converted toList<Integer>usingIntStreamwith boxing:
int[] array = new int[]{42, 5, 1, 3, 4};
List<Integer> list = new ArrayList<>(Arrays.stream(array).boxed().toList());
System.out.println(list.get(0));
- Another way to create
IntStreamfromint[]is to useIntStream.of():
int[] array = new int[]{42, 5, 1, 3, 4};
List<Integer> list = new ArrayList<>(IntStream.of(array).boxed().toList());
System.out.println(list.get(0));
All three fixes will work as expected, and the code will print 42.
As a conclusion, don't ignore IDE warnings, as they can indicate real bugs, not just code smells.
Dream your code, code your dream.
Top comments (0)