01: // Copyright 2006 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry.internal.util;
16:
17: import java.util.Arrays;
18:
19: /**
20: * Combines multiple values to form a single composite key. MultiKey can often be used as an
21: * alternative to nested maps.
22: */
23: public final class MultiKey {
24: private static final int PRIME = 31;
25:
26: private final Object[] _values;
27:
28: private final int _hashCode;
29:
30: /**
31: * Creates a new instance from the provided values. It is assumed that the values provided are
32: * good map keys themselves -- immutable, with proper implementations of equals() and
33: * hashCode().
34: *
35: * @param values
36: */
37: public MultiKey(Object... values) {
38: _values = values;
39:
40: _hashCode = PRIME * Arrays.hashCode(_values);
41: }
42:
43: @Override
44: public int hashCode() {
45: return _hashCode;
46: }
47:
48: @Override
49: public boolean equals(Object obj) {
50: if (this == obj)
51: return true;
52: if (obj == null)
53: return false;
54: if (getClass() != obj.getClass())
55: return false;
56: final MultiKey other = (MultiKey) obj;
57:
58: return Arrays.equals(_values, other._values);
59: }
60:
61: @Override
62: public String toString() {
63: StringBuilder builder = new StringBuilder("MultiKey[");
64:
65: boolean first = true;
66:
67: for (Object o : _values) {
68: if (!first)
69: builder.append(", ");
70:
71: builder.append(o);
72:
73: first = false;
74: }
75:
76: builder.append("]");
77:
78: return builder.toString();
79: }
80:
81: }
|