4

In Java, using java.util.Arrays, the following codes:

float[] arr = {(float)0.2, (float)4.5};
Float[] brr = {new Float(0.2), new Float(4.5)};
Float x = new Float(4.5);
float y = (float)4.5;
System.out.println(Arrays.asList(arr).indexOf(x));
System.out.println(Arrays.asList(arr).indexOf(y));
System.out.println(Arrays.asList(brr).indexOf(x));
System.out.println(Arrays.asList(brr).indexOf(y));

gives

-1
-1
1
1

My question: How can I search for the index of 4.5 in the array arr?

I thought that Arrays.asList(arr) makes a list of objects from arr but it does not behave like the other array, brr.

Santosa Sandy
  • 217
  • 6
  • 20
ewi
  • 175
  • 1
  • 9

3 Answers3

6

Arrays.asList takes a T... as the argument. When the parameter is an array of objects, it is passed as if you wrote Arrays.asList(new Float(0.2), new Float(4.5)).

In your second case, the parameter is an array of primitives. Here, the Java compiler decides to treat the entire array as a single object. Hence, you will be passing an array containing a single element, the array of floats.

To confirm this, try the following:

Arrays.asList(arr).indexOf(arr) // returns 0

Since the method is typed as <T> List<T> asList(T...ts) only the second of this statements are allowed:

    System.out.println(Arrays.<Float>asList(arr).indexOf(x)); //Error
    System.out.println(Arrays.<Float>asList(brr).indexOf(x)); //List<Float>

The first one of primitive types cannot be typed as Float at the argument.

The statement to convert it to a List is the following:

 List<float[]> l = Arrays.<float[]>asList(arr); //The array is the only index in the List
Marcos Vasconcelos
  • 18,136
  • 30
  • 106
  • 167
Andrew Sun
  • 4,101
  • 6
  • 36
  • 53
0

Yes It behaves like this. The problem is you do not create arr as Float object array. Instead you make the array of primitive.

Try this code

Float[] arr = {(float)0.2, (float)4.5};
Float[] brr = {new Float(0.2), new Float(4.5)};
float x = 0.2f;
float y = (float)4.5;
System.out.println(Arrays.asList(arr).indexOf(x));
System.out.println(Arrays.asList(arr).indexOf(y));
System.out.println(Arrays.asList(brr).indexOf(x));
System.out.println(Arrays.asList(brr).indexOf(y));

This code will provide you your desired output

Naresh Bharadwaj
  • 192
  • 1
  • 12
0

Arrays.asList(arr), if arr is an array of primitives, creates a list of a single element, which is the array itself.

I.e.:

    float[] arr = {(float)0.2, (float)4.5};

    System.out.println(Arrays.asList(arr).get(0).getClass().getSimpleName());
      // Prints "float[]"
    System.out.println(Arrays.asList(arr).size());
      // Prints "1"
Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103