`
貌似掉线
  • 浏览: 256694 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

一一对应的键值对象

阅读更多
最近写程序需要用到一种结构,像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 (msdx.android@tom.com)
 */
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));
	}
}
0
4
分享到:
评论
2 楼 貌似掉线 2013-03-27  
xiaozhi6156 写道
很好〈。。。。。。。。。〉

不过后来我发现完全没必要自己写。因为在我自己的需求中,用的都是int的键值对。android中有SparseArray和SparseIntArray。对于从value取得key,虽然没有直接的可调用方法,不过有一个方法是从value中取得index,有一个是从index中取得key,就是不知道这个类的效率怎么样。
1 楼 xiaozhi6156 2013-03-26  
很好〈。。。。。。。。。〉

相关推荐

Global site tag (gtag.js) - Google Analytics