Fundamentals 9 min read

Common Java Practices and Idioms: equals, hashCode, compareTo, clone, I/O, Threads, and More

This article compiles essential Java programming idioms—including proper implementations of equals, hashCode, compareTo, and clone, efficient use of StringBuilder, safe random number generation, iterator removal, thread creation, try‑finally handling, I/O streams, array operations, and defensive checks—providing practical guidance beyond the official language specification.

Qunar Tech Salon
Qunar Tech Salon
Qunar Tech Salon
Common Java Practices and Idioms: equals, hashCode, compareTo, clone, I/O, Threads, and More

In Java programming, many useful idioms are not obvious from the language specification; this article collects frequently‑used patterns such as implementing equals(), hashCode(), compareTo(), and clone() correctly.

For equals(), the parameter must be an Object, it should return false for null, primitive fields are compared with ==, and arrays of primitives with Arrays.equals(). Always override hashCode() consistently.

The contract for hashCode() requires equal objects to have identical hash codes; returning a constant (e.g., 0) is legal but degrades performance. Implementations should aim for good distribution.

When implementing compareTo(), prefer the generic Comparable<T> interface, focus only on the sign of the result, and note that Comparator.compare() follows a similar pattern.

For clone(), call super.clone() for a shallow copy, manually deep‑copy mutable fields, and never let CloneNotSupportedException escape a class that implements Cloneable.

Use StringBuilder (or StringBuffer when synchronization is needed) with append() and toString() instead of repeated string concatenation ( s += item) to avoid O(n²) time.

Generate a random integer within a range using java.util.Random.nextInt(int); avoid biased approaches such as Math.abs(rand.nextInt()) % n which can produce negative results.

When using Iterator.remove(), call it only once per element and only after a successful next() call.

Reversing a string can be done with StringBuilder.reverse(), a method that could be considered for inclusion in the standard library.

To start a new thread, always invoke Thread.start() rather than calling run() directly. The article shows three ways: implementing Runnable, extending Thread, and using an anonymous subclass of Thread.

Use try‑finally blocks to guarantee resource release; the finally block runs unless the JVM terminates abruptly.

Reading bytes from an InputStream returns a value 0‑255 or -1 at end‑of‑stream; reading into a buffer may return fewer bytes than requested, so the returned length must be handled.

When reading text files, BufferedReader.readLine() returns null at end‑of‑stream, and you can wrap any InputStream (e.g., sockets) with InputStreamReader for character conversion.

Writing text can be done with PrintWriter or OutputStreamWriter, which also separate byte and character handling.

Defensive checking should verify numeric ranges, non‑null object parameters, and array index or range bounds before use.

Array utilities include filling with <code>Arrays.fill(a, (byte)123);, copying a range with <code>System.arraycopy(a, 3, b, 6, 8);, and resizing using Arrays.copyOf or Arrays.copyOfRange.

Packing four bytes into an int and unpacking back to bytes should use the unsigned right‑shift operator ( >>>) rather than the signed shift ( >>).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Core APIidioms
Qunar Tech Salon
Written by

Qunar Tech Salon

Qunar Tech Salon is a learning and exchange platform for Qunar engineers and industry peers. We share cutting-edge technology trends and topics, providing a free platform for mid-to-senior technical professionals to exchange and learn.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.