Why does indexof fail for arrays convert to lists in java?

Let's say I have a boolean array in which I want to find the first "true" record. Since there is no indexOf method in the Java array, I decided to do it like this:

boolean[] bArr = new boolean[]{true, true, true, true, true};
int index = Arrays.asList(bArr).indexOf(true);

      

Now why does this cause the index to be -1 (ie "no true found").

compiled: http://ideone.com/DdNoVw

+3


source to share


1 answer


Because it Arrays.asList(bArr)

does List<boolean[]>

not create a List<Boolean>

. Arrays.asList

does not put the array boolean[]

into an array boolean[]

(note the difference).

Hence, you only have a list with one boolean array at index 0.

If you used Boolean[] bArr = new Boolean[]{true, true, true, true, true};

, it index

will be 0.



Thus, the ways to overcome this problem:

  • create an empty list, loop through your array and add each item to the list (each boolean will be put into a boolean)
  • write a simple utility method that takes an array boolean[]

    as a parameter and a value to be found
+10


source







All Articles