Java hands out references in the order objects are created, starting at
@1001. Fill in the memory picture for when main finishes.Names
top level: start = @1001, x = @1002, y = @1003, more =
y.doubled() on , returns @1004
main()
x.addOne() on
Heap
@1001:
@1002: Bag[counts=@1001]
@1003: Bag[counts=]
@1004:
top level: start = @1001, x = @1002, y = @1003, more =
y.doubled() on , returns @1004
main()
x.addOne() on
Heap
@1001:
@1002: Bag[counts=@1001]
@1003: Bag[counts=]
@1004:
Still at the end of
main, what does each expression produce?x == y
x.equals(y)
start == y.counts
Arrays.equals(start, more)
x.equals(y)
start == y.counts
Arrays.equals(start, more)
This test fails. Why?
record Bag(int[] counts) { }
void main() {
assertEquals(new Bag(new int[]{ 1, 2 }), new Bag(new int[]{ 1, 2 }));
}- The two
countsfields hold different arrays, and a record’sequalscompares an array field with the array’s ownequals, which checks the reference. assertEqualscompares the twoBags with==.assertEqualsuses.equals(), not==. That is why twoCars with onlyStringandintfields passed.- The two arrays have different contents.Both arrays are
{ 1, 2 }. Their contents are the same; they are just two separate arrays. - Records always compare by reference.A record with only
Stringandintfields passes this kind of test, like the firstCar. It’s the array field that compares by reference.