Reputation: 11912
Found this website to presumably test wannabe developers...
http://www.devchallenge.co.uk/challenge-2
The question is this...
Based on the given code, which of the following tests will return a ‘true’ answer and pass, and which will return a ‘false’ answer and fail?
ArrayList array1 = new ArrayList();
ArrayList array2 = new ArrayList();
array1.add(1);
array1.add(2);
array1.add("Aviva");
array2.add(1);
array2.add(2.0);
array2.add("Aviva");
Asserts
Equality
(array1[0],array2[0]);
Asserts
Equality
(array1[1],array2[1]);
Asserts
Equality
(array1[2],array2[2]);
Apparently the answer is 'Fail', 'Fail', 'Pass'.
I'm not a Java developer - and I am presuming this challenge is in Java (though it isn't stated).
What exactly is Equality doing? Is it checking for the same object or the same value? I know that some objects are interned into the String/Integer pool in Java and so I can understand why the last one is true. But why is the first one not true?
Upvotes: 1
Views: 149
Reputation: 39651
This is not valid Java syntax. You cannot call Asserts Equality ()
.
As an assert in a JUnit test this has to be Assert.assertEquals(array[0], array2[0])
which would cause comparing two Integer
s. So this should pass.
So I don't understand your proposed results of that code also. I would say pass, fail, pass is right.
Upvotes: 1
Reputation: 19443
If the scalars are being "auto-boxed" then they will have different object holders, so a tests of == will be false, but the strings will pass the == test since the compiler makes sure the same exact string as a constant is used. If you are considering an .equals() test, then they will all be equal.
Upvotes: 1