j.ul.Objects follow-up: methods for var-argification? (original) (raw)

Joseph D. Darcy Joe.Darcy at Sun.COM
Mon Oct 12 17:25:42 UTC 2009


Joshua Bloch wrote:

Joe,

I'm not sure I like this idea. My one experience with forcing an array method to do double duty as varargs method was a disaster. The method was Arrays.asList, and the result was Puzzler # 7 from "The Continuing Adventures of Java™Puzzlers: Tiger Traps." Here it is: 7. “Fib O’Nacci” public class Fibonacci { private static final int LENGTH = 7; public static void main(String[] args) { int[] fib = new int[LENGTH]; fib[0] = fib[1] = 1; // First 2 Fibonacci numbers for (inti = 2; i < LENGTH; i++)_ _fib[i] = fib[i -2] + fib[i -1];_ _System.out.println(Arrays.asList(fib));_ _}_ _}_ _The main moral of the puzzle was:_ _Use varargssparingly in your APIs_ _•It can hide errors and cause confusion_ _•This program wouldn't compile under 1.4_ _Arrays.hashCode, equals, and toString are already overloaded out the_ _wazoo; adding varargs to the mix could be deadly. Also, Arrays is not_ _the place where people would go looking for what is essentially a_ _hashing utility. So I'm not in favor of varargifying the existing_ _methods in Arrays, but I am in favor of adding a convenience method_ _like this somewhere:_ _/**_ _* Generates a hash code for a sequence of input values. The hash_ _code is_ _* generated as if all the input values were placed into an array,_ _and that_ _* array were hashed by calling {@link Arrays#hashCode(Object[])}._ _*

*

This method is useful for implementing {@link

Object#hashCode()} on * objects containing multiple fields. For example, if an object that has * three fields, {@code x}, {@code y}, and {@code z}, one could write: *
* @Override public int hashCode() { * return Objects.hashCode(x, y, z); * } * * Warning: When a single object reference is supplied, the returned * value does not equal the hash code of that object reference. This * value can be computed by calling {@link #hashCode(Object)}. */ public static int hash(Object... components) { return Arrays.hashCode(components); } Viewed in isolation, it's simple, straightforward, and will help people write high quality hashCode methods. I don't think Objects is a bad place for it, but you could put it is a "hash utility" class if we wrote such a thing.

Okay; unless and until a hash utility is added somewhere, this hash(Object ...) can live in Objects.

-Joe



More information about the core-libs-dev mailing list