Schönheitsfrage

Hallo,

schau mal hier:
Java:
package de.tutorials;

import java.util.Arrays;

public class HashCodeExample {

  /**
   * @param args
   */
  public static void main(String[] args) {
    Key a = new Key(473892, 4711);
    Key b = new Key(4711, 473892);

    System.out.println(a.equals(a));
    System.out.println(b.equals(b));
    System.out.println(a.equals(b));
    System.out.println(b.equals(a));
    System.out.println(a.hashCode() == b.hashCode());

    System.out.println(a);
    System.out.println(b);
  }

  static class Key {
    private final Object[] components;
    private final int hash;


    public Key(Object... components) {
      Object[] c = components.clone();
      Arrays.sort(c);
      this.components = c;
      this.hash = Arrays.hashCode(c);
    }


    @Override
    public int hashCode() {
      return hash;
    }


    @Override
    public boolean equals(Object obj) {
      if (this == obj) return true;
      if (obj == null) return false;
      if (getClass() != obj.getClass()) return false;
      Key other = (Key) obj;
      if (!Arrays.equals(components, other.components)) return false;
      if (hash != other.hash) return false;
      return true;
    }


    @Override
    public String toString() {
      return Arrays.toString(components);
    }
  }
}

Gruß Tom
 
Zurück