0

Given code:

float []    f3 = {2.7f};
float [] [] f2 = {{42.0f}, {1.7f, 1.9f}};

What should I understand by statement if(f2[1]==f3)? The result is false, but are we comparing their sizes?

Tomek Rękawek
  • 9,204
  • 2
  • 27
  • 43
  • 1
    `==` is referential equality. `a == b` is true only if `a` and `b` are *the same reference*. It doesn't matter how big they are or what's in them. – Chris Martin Apr 09 '14 at 07:19

3 Answers3

1

You are comparing references, because in Java arrays are objects: Since these are different objects, you will get false.

If you had this:

int[] f3 = { 100 };
int[][] f2 = { f3, { 2, 1 } };

System.out.println(f2[0] == f3);

The output would be true because you are adding the reference f3 as an element of the array f2.

Community
  • 1
  • 1
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
0

f2[1] == f3 compares references to different float[] instances and it will never return true. Use Arrays.equals instead

ifloop
  • 8,079
  • 2
  • 26
  • 35
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

f2[1]==f3 tests if f2[1] points to the same address as f3. Thus even if you write

float [] f3={1.7f,1.9f};
float [] [] f2={{42.0f},{1.7f,1.9f}};

it will still come back false. Only if you assign

f2[1] = f3;

or vice versa f2[1]==f3 will be true.

Adaephon
  • 16,929
  • 1
  • 54
  • 71
snOOfy
  • 33
  • 6