View Javadoc

1   package cz.cuni.amis.utils;
2   
3   /**
4    * N-argument key - used to store multiple keys within one object to provide n-argument key for maps.
5    * <p><p>
6    * The keys are not commutative! If you need to have commutativity for key's parameters use {@link NKeyCommutative}.
7    *
8    * @author jgemrot
9    */
10  public class NKey {
11  
12  	private Object[] keys;
13  	private int hashCode;
14  
15  	/**
16  	 * Should be used by descendants together with init()
17  	 */
18  	protected NKey() {
19  
20  	}
21  
22  	public NKey(Object... keys) {
23  		init(keys);
24  	}
25  
26  	protected void init(Object[] keys) {
27  		this.keys = keys;
28  		HashCode hc = new HashCode();
29  		for (Object key : keys) {
30  			hc.add(key);
31  		}
32  		this.hashCode = hc.getHash();
33  	}
34  
35  	@Override
36  	public int hashCode() {
37  		return this.hashCode;
38  	}
39  
40  	@Override
41  	public boolean equals(Object obj) {
42  		if (obj == null) return false;
43  		if (obj.hashCode() != hashCode()) return false;
44  		if (!(obj instanceof NKey)) return false;
45  		NKey key = (NKey)obj;
46  		if (getCount() != key.getCount()) return false;
47  		for (int i = 0; i < getCount(); ++i) {
48  			if (!SafeEquals.equals(keys[i], key.getKey(i))) return false;
49  		}
50  		return true;
51  	}
52  
53  	public int getCount() {
54  		return keys.length;
55  	}
56  
57  	public Object getKey(int index) {
58  		return keys[index];
59  	}
60  
61  	@Override
62  	public String toString() {
63  		StringBuffer sb = new StringBuffer();
64  		sb.append("NKey[");
65  		if (keys.length > 0) {
66  			sb.append(keys[0]);
67  			for (int i = 1; i < keys.length; ++i) {
68  				sb.append(", ");
69  				sb.append(keys[i]);
70  			}
71  		}
72  		sb.append("]");
73  		return sb.toString();
74  	}
75  
76  }