[BAEL-6960] value based class (#14785)
* [BAEL-6960] value based class * [BAEL-6960] value based class * [BAEL-6960] value based class --------- Co-authored-by: Bhaskar <bhaskar.dastidar@freshworks.com>
This commit is contained in:
parent
9d0985112b
commit
d6db7fd6e7
|
@ -0,0 +1,49 @@
|
|||
package com.baeldung.value_based_class;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import jdk.internal.ValueBased;
|
||||
|
||||
/**
|
||||
* This class is written with the intention that it can serve as an example of
|
||||
* what a Value-based class could be.
|
||||
*/
|
||||
|
||||
@ValueBased
|
||||
public final class Point {
|
||||
private final int x;
|
||||
private final int y;
|
||||
private final int z;
|
||||
|
||||
private static Point ORIGIN = new Point(0, 0, 0);
|
||||
|
||||
private Point(int x, int y, int z) {
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
this.z = z;
|
||||
}
|
||||
|
||||
public static Point valueOfPoint(int x, int y, int z) {
|
||||
// returns a cached instance if it is origin, or a new instance
|
||||
if (isOrigin(x, y, z))
|
||||
return ORIGIN;
|
||||
return new Point(x, y, z);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object other) {
|
||||
if (other == null || getClass() != other.getClass())
|
||||
return false;
|
||||
Point point = (Point) other;
|
||||
return x == point.x && y == point.y && z == point.z;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(x, y, z);
|
||||
}
|
||||
|
||||
private static boolean isOrigin(int x, int y, int z) {
|
||||
return x == 0 && y == 0 && z == 0;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,41 @@
|
|||
package com.baeldung.value_based_class;
|
||||
|
||||
import org.junit.Assert;
|
||||
import org.junit.Test;
|
||||
|
||||
public class ValueBasedClassUnitTest {
|
||||
@Test
|
||||
public void givenAutoboxedAndPrimitive_whenCompared_thenReturnEquals() {
|
||||
int primitive_a = 125;
|
||||
Integer obj_a = 125; // this is autoboxed
|
||||
Assert.assertSame(primitive_a, obj_a);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueBasedPoint_whenCreated_thenReturnsObjects() {
|
||||
Point p1 = Point.valueOfPoint(1, 2, 3);
|
||||
Point p2 = Point.valueOfPoint(2, 3, 4);
|
||||
|
||||
Assert.assertNotEquals(p1, p2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueBasedPoint_whenCompared_thenReturnEquals() {
|
||||
Point p1 = Point.valueOfPoint(1, 2, 3);
|
||||
Point p2 = Point.valueOfPoint(1, 2, 3);
|
||||
|
||||
Assert.assertEquals(p1, p2);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void givenValueBasedPoint_whenOrigin_thenReturnCachedInstance() {
|
||||
Point p1 = Point.valueOfPoint(0, 0, 0);
|
||||
Point p2 = Point.valueOfPoint(0, 0, 0);
|
||||
Point p3 = Point.valueOfPoint(1, 2, 3);
|
||||
|
||||
// the following should not be assumed for value-based classes
|
||||
|
||||
Assert.assertTrue(p1 == p2);
|
||||
Assert.assertFalse(p1 == p3);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue