View Javadoc

1   package cz.cuni.amis.utils;
2   
3   import java.util.Arrays;
4   import java.util.Comparator;
5   
6   /**
7    * N-Key used for maps.
8    * <p><p>
9    * Remember that all passed "commutatives" are flatted (but within the commutatives parts)!
10   * <p><p>
11   * NKeyCommutative can be equal to NKey and vice versa!
12   *
13   * @author jgemrot
14   *
15   */
16  public class NKeyCommutative extends NKey {
17  
18  	@SuppressWarnings("unchecked")
19  	private Comparator HASH_CODE_COMPARATOR = new Comparator() {
20  
21  		@Override
22  		public int compare(Object arg0, Object arg1){
23  			if (arg0 == null) {
24  				if (arg1 == null) return 0;
25  				return -1;
26  			}
27  			if (arg1 == null) return 1;
28  			return arg0.hashCode() - arg1.hashCode();
29  		}
30  
31  	};
32  
33  	public NKeyCommutative(Object[]... commutatives) {
34  		if (commutatives.length == 1) {
35  			Arrays.sort(commutatives[0], HASH_CODE_COMPARATOR);
36  			init(commutatives[0]);
37  		} else {
38  			int length = 0;
39  			for (Object[] c : commutatives) {
40  				Arrays.sort(c, HASH_CODE_COMPARATOR);
41  				length += c.length;
42  			}
43  			Object[] keys = new Object[length];
44  			int index = 0;
45  			for (Object[] c : commutatives) {
46  				System.arraycopy(c, 0, keys, index, c.length);
47  				index += c.length;
48  			}
49  			init(keys);
50  		}
51  	}
52  
53  }