一一对应的键值对象

最近写程序需要用到一种结构,像HashMap的,但是却是一对一的这种结构。网上查询未果,自己用两个ArrayList进行封装。现在写出来以作抛砖引玉,希望得到大家的相关意见及建议。
/*  
 * @(#)DoubleKeyMap.java              Project:RTKSETTINGS  
 * Date:2013-1-9  
 *  
 * Copyright (c) 2013 Geek_Soledad.  
 * All rights reserved.  
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");  
 *  you may not use this file except in compliance with the License.  
 * You may obtain a copy of the License at  
 *  
 *     http://www.apache.org/licenses/LICENSE-2.0  
 *  
 * Unless required by applicable law or agreed to in writing, software  
 * distributed under the License is distributed on an "AS IS" BASIS,  
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
 * See the License for the specific language governing permissions and  
 * limitations under the License.  
 */
package com.realtek.msdx.rtksettings.util;

import java.util.ArrayList;

/**
 * 一对一的双键类。
 * 
 * @author Geek_Soledad ([email protected])
 */
public class DoubleKeyMap<K1, K2> {

	private ArrayList<K1> key1s;
	private ArrayList<K2> key2s;

	public DoubleKeyMap() {
		key1s = new ArrayList<K1>();
		key2s = new ArrayList<K2>();
	}

	/**
	 * 加入一一对应的双键。
	 * 
	 * @param k1
	 *            键1
	 * @param k2
	 *            键2
	 */
	public DoubleKeyMap<K1, K2> add(K1 k1, K2 k2) {
		if (k1 == null || k2 == null) {
			throw new IllegalArgumentException(
					"both the parameters could not be null.");
		}
		if (key1s.contains(k1)) {
			throw new IllegalArgumentException("the key1 has been put");
		}

		if (key2s.contains(k2)) {
			throw new IllegalArgumentException("the key2 has been put");
		}
		key1s.add(k1);
		key2s.add(k2);
		return this;
	}

	/**
	 * 由键2取得键1
	 * 
	 * @param k2
	 *            键2
	 * @return 返回对应的键1
	 */
	public K1 getKey1(K2 k2) {
		return key1s.get(key2s.indexOf(k2));
	}

	/**
	 * 由键1 取得键2
	 * 
	 * @param k1
	 *            键1
	 * @return 返回对应的键2
	 */
	public K2 getKey2(K1 k1) {
		return key2s.get(key1s.indexOf(k1));
	}
}

你可能感兴趣的:(java,HashMap,一对一键值对,一一对应)