| Author |
doubt in List.indexOf()
|
Fissehaye Kahsay
Greenhorn
Joined: May 26, 2009
Posts: 9
|
|
Hi ranchers
why are the two outputs in the following code -1(unfound). As you can see, there is 4 in the array and I created a list using Array.asList()
|
 |
Evan Caballero
Ranch Hand
Joined: Dec 10, 2009
Posts: 59
|
|
here it is :
I think that when the JVM autoboxes int to Integer, the Integer.equals() method is ignored or something like that.
|
 |
William Brogden
Author and all-around good cowpoke
Rancher
Joined: Mar 22, 2000
Posts: 12269
|
|
Looks like the indexOf is using identity of the reference, not the content of the object.
Bill
|
Java Resources at www.wbrogden.com
|
 |
Fissehaye Kahsay
Greenhorn
Joined: May 26, 2009
Posts: 9
|
|
thanks for your help
but how can I get the index of 4 in the int[] not in Integer[] ?. I'm forced to use the int[] instead of Integer[] (just calling a method which takes int[])
|
 |
Evan Caballero
Ranch Hand
Joined: Dec 10, 2009
Posts: 59
|
|
In fact, when you do i.asList(), it returns a list of int[] (List<int[]>) with one element :/
like [{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }]
so, there is no element at index 4 ; there is only an element at index 0, which is your original int[].
the asList method considers that you want to build a list from one int[], which IS an object. It is like if you were doing Arrays.asList(i1, i2, i3, i4), where i1 i2 i3 and i4 are int[] objects.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Evan is right. Arrays.asList will only work on objects, not on primitives. You will need to box the entire array - convert each element into Integer objects first. You may want to switch to a "regular" List implementation:
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
 |
|
|
subject: doubt in List.indexOf()
|
|
|