hashCode/equals, reading JSON and .properties, Jackson and POJOs
If two objects are equal by equals, their hashCode values must match, so both methods are overridden together. A hash collection finds a bucket by the hash and calls equals only there, so equals without hashCode breaks contains. Test data is read from the classpath, not by a relative path. Jackson turns JSON into a POJO: in version 2 an unknown field fails, in version 3 it is ignored by default.
Java · Data
Two Users with identical fields, and set.contains says false. Where did the object go?
A test creates the expected user, puts it into a HashSet and looks for it among those returned by the API. All fields match, equals is overridden, and contains returns false. In a neighbouring test users.json is read with a path relative to the working directory, and on CI the test fails with FileNotFoundException. A third test fails on UnrecognizedPropertyException because the backend added a new field to the response.
All of it is about one thing: how objects are compared in hash collections in Java, and how test data gets into memory from files. The lesson has two parts: the equals and hashCode contract, then reading resources, .properties and Jackson.
How it works and why it is designed so
The contract is this: if a.equals(b), then a.hashCode() == b.hashCode(). The reverse is not required: different objects may have the same hash (a collision). HashMap and HashSet first compute the hash to find a "bucket" and only inside it compare elements through equals. This is how lookup takes roughly constant time instead of scanning all elements. If only equals is overridden, two equal objects get different hashes (the default hashCode is based on object identity), land in different buckets, and contains does not match them.
class User {
private final String email;
private final String role;
User(String email, String role) { this.email = email; this.role = role; }
@Override public boolean equals(Object o) {
return o instanceof User u && email.equals(u.email) && role.equals(u.role);
}
// hashCode is not overridden
}
Set<User> set = new HashSet<>();
set.add(new User("a@x.com", "admin"));
set.contains(new User("a@x.com", "admin")); // usually false
The word "usually" is honest: with a hash coincidence the result would be true, so the bug may come and go. The fix: both methods built from the same fields.
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User u)) return false;
return Objects.equals(email, u.email) && Objects.equals(role, u.role);
}
@Override public int hashCode() {
return Objects.hash(email, role); // the same fields as in equals
}
// shortest: a record generates both methods from all components
record UserRec(String email, String role) {}
A lookup in a HashSet
Different hashes, different buckets
Objects equal by fields land in different buckets, and contains never even reaches equals.
One hash, one bucket
The hash leads to the right bucket and equals confirms the match.
There are two traps around this. The first: a key or element whose fields enter the hash must not be changed after it is added to the collection. The object stays in the bucket of the old hash, and contains looks in the bucket of the new one:
Set<MutableUser> set = new HashSet<>();
MutableUser u = new MutableUser("a@x.com"); // a mutable class with equals/hashCode
set.add(u);
u.setEmail("b@x.com");
set.contains(u); // false: sits in the old hash's bucket
The second: equals without hashCode breaks not only HashSet but also HashMap, distinct() in streams and groupingBy. If you do not want to add equals to a class just for a test, compare fields recursively: assertThat(actual).usingRecursiveComparison().isEqualTo(expected) (AssertJ) shows exactly which field differs. Lombok @EqualsAndHashCode also generates both methods together.
Test data files and configuration
Files from src/test/resources end up on the classpath, so they must be read through the classpath, not through a relative path: the working directory differs in an IDE, in Maven and in Docker.
private static final ObjectMapper MAPPER = new ObjectMapper();
static List<User> loadUsers() throws IOException {
try (InputStream in = Objects.requireNonNull(
UserData.class.getResourceAsStream("/users.json"),
"users.json not found on the classpath")) {
return MAPPER.readValue(in, new TypeReference<List<User>>() {});
}
}
The leading / means the classpath root. If the resource is missing, getResourceAsStream returns null without an exception, so an explicit check with a message gives a clear error instead of a NullPointerException somewhere in Jackson.
.properties files are read through Properties. Values are usually chosen by priority: a system property (-DbaseUrl=…), then an environment variable, then the file, then a default:
Properties props = new Properties();
try (Reader in = new InputStreamReader(
Config.class.getResourceAsStream("/config.properties"), StandardCharsets.UTF_8)) {
props.load(in);
}
String baseUrl = System.getProperty("baseUrl", props.getProperty("baseUrl", "http://localhost:8080"));
String token = System.getenv("API_TOKEN"); // secrets do not live in the repository
The load(InputStream) method reads the file as ISO-8859-1, so for Cyrillic load(Reader) with UTF-8 is handier, as above. Do not keep secrets (passwords, tokens) in a file in the repository: take them from environment variables or the CI secret store.
Jackson (ObjectMapper) turns JSON into a POJO and back. A POJO is a plain class or record with fields and accessors, with no dependency on a framework. What to know:
- Deserialisation needs a no-argument constructor with setters, or a
record(Jackson from 2.12), or a constructor with@JsonCreator. - In Jackson 2.x an unknown field in JSON gives
UnrecognizedPropertyExceptionby default (FAIL_ON_UNKNOWN_PROPERTIES). For responses that may grow, add@JsonIgnoreProperties(ignoreUnknown = true)or turn the option off in the mapper. In contract tests strict behaviour is useful: it catches unexpected fields. The choice depends on whether a test should fail when a field is added. @JsonProperty("user_id")binds a field to another name. ForLocalDateandInstantin 2.x you need thejackson-datatype-jsr310module (JavaTimeModule), and to write dates as ISO strings you disableWRITE_DATES_AS_TIMESTAMPS.- Numbers in
Map<String, Object>becomeInteger,LongorDouble; for amounts enableUSE_BIG_DECIMAL_FOR_FLOATSor declare the field asBigDecimal. ObjectMapperis thread-safe after configuration: create one instance and reuse it, because creation is expensive.
ObjectMapper mapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.build();
Jackson 3. The new major version moves the databind packages and coordinates to tools.jackson (annotations stay in com.fasterxml.jackson.annotation), makes ObjectMapper immutable (it is built through JsonMapper.builder()), turns FAIL_ON_UNKNOWN_PROPERTIES off by default and builds in java.time support. If the project pulls libraries that depend on Jackson 2, both versions can coexist thanks to different packages, but mappers are not interchangeable.
Common mistakes
- Only
equalswithouthashCode, socontainsworks sometimes and not others. - Mutable fields in a map key or a set element.
- A relative path to test files: works from the IDE, fails on CI.
- Secrets in
.propertiesthat ended up in the repository. - A new
ObjectMapperin every test and strict deserialisation where checking the needed fields is enough.
Check yourself
The class Order overrides equals by id but not hashCode. What error does this give in a HashSet<Order>?
Answer
Equal orders have different hashes and lie in different buckets, so contains usually does not find an equal element and a "duplicate" can be added to the set. Override both methods from id.
A test fails on CI with FileNotFoundException on new File("src/test/resources/users.json") but works in the IDE. Why, and what to change?
Answer
The path is relative to the working directory, which differs between runs. Read from the classpath: getResourceAsStream("/users.json"), because resources from src/test/resources go on the classpath.
The API added a new field to the response and a test with Jackson 2 failed on UnrecognizedPropertyException. What can you do and what is the trade-off?
Answer
Add @JsonIgnoreProperties(ignoreUnknown = true) or turn off FAIL_ON_UNKNOWN_PROPERTIES: the test stops failing on added fields. The trade-off: the signal about unexpected contract changes is lost, so strict contract checks keep the strict mode.
equals, their hashCode values must match, so the methods are overridden together. Test files live in src/test/resources, and Jackson turns JSON into a POJO. Middle/Senior: I explain the mechanics: the hash leads to a bucket, equals compares inside it, so mutable fields in a key break lookup. For comparisons in tests I use a record or usingRecursiveComparison. I read resources from the classpath with an explicit null check, and settings priority is -D, environment, file. In Jackson I choose strictness toward unknown fields deliberately and remember that Jackson 3 changed the packages and defaults.