01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one or more
03: * contributor license agreements. See the NOTICE file distributed with
04: * this work for additional information regarding copyright ownership.
05: * The ASF licenses this file to You under the Apache License, Version 2.0
06: * (the "License"); you may not use this file except in compliance with
07: * the License. You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: package java.beans;
19:
20: /**
21: * A simple map.
22: * Keys are equal iff they are the same object (reference equals).
23: * The put() do not check key duplication, so always do a get() before put().
24: * Noop if either key or value is null.
25: *
26: */
27: class ReferenceMap {
28:
29: private static class Pair {
30: Object key;
31:
32: Object value;
33:
34: Pair(Object key, Object value) {
35: this .key = key;
36: this .value = value;
37: }
38: }
39:
40: private static final int GROWING_UNIT = 16;
41:
42: private Pair pairs[] = new Pair[GROWING_UNIT];
43:
44: private int size = 0;
45:
46: public void clear() {
47: size = 0;
48: }
49:
50: public Object get(Object key) {
51: if (key == null) {
52: return null;
53: }
54: for (int i = size - 1; i >= 0; i--) {
55: Pair p = pairs[i];
56: if (p.key == key) {
57: return p.value;
58: }
59: }
60: return null;
61: }
62:
63: public void put(Object key, Object value) {
64: if (key == null || value == null) {
65: return;
66: }
67:
68: // grow pairs if necessary
69: if (pairs.length <= size) {
70: int newLength = pairs.length + GROWING_UNIT;
71: while (newLength <= size) {
72: newLength += GROWING_UNIT;
73: }
74: Pair newPairs[] = new Pair[newLength];
75: System.arraycopy(pairs, 0, newPairs, 0, size);
76: pairs = newPairs;
77: }
78:
79: pairs[size++] = new Pair(key, value);
80: }
81:
82: public Object remove(Object key) {
83: if (key == null) {
84: return key;
85: }
86: for (int i = size - 1; i >= 0; i--) {
87: Pair p = pairs[i];
88: if (p.key == key) {
89: pairs[i] = pairs[--size];
90: return p.value;
91: }
92: }
93: return null;
94: }
95:
96: }
|