首页 新闻 论坛 群组 Blog 文档 下载 读书 Tag 网摘 搜索 .NET Java 游戏 视频 人才 外包 数据库 第二书店 程序员

Tag/ 


共1个网摘 [ 1 ]   |  

HashMap中的对象根据成员进行自定义排序

wuwzh收录,使用标签:HashMap中的对象根据成员进行自定义排序,时间:2007-12-12 23:00:30 | 相关网摘我也收藏

Map是Java中最常用的存储对象的集合类之一,存储在HashMap中的对象在取出时是无序的,下文以示例介绍了如果对HashMap中存储的对象根据成员进行自定义排序。

应用说明:计算缓存对象的点击次数按次数排序输出。

1. 定义CacheObj类

定义了一个简单的对象,这个对象将存储在一个HashMap中,希望根据CacheObj中的整型成员变量cachedCounter进行排序输出。




/*
* Created on 2003-3-5
*/
package com.cache;
/**
* @author Weidong
*
*/
public class CacheObj {
int cachedCounter;
Object cacheObj = null;
/**
* @return Returns the cacheObj.
*/
public Object getCacheObj() {
return cacheObj;
}
/**
* @param cacheObj
* The cacheObj to set.
*/
public void setCacheObj(Object cacheObj) {
this.cacheObj = cacheObj;
}
/**
* @return Returns the cachedCounter.
*/
public int getCachedCounter() {
return cachedCounter;
}
/**
* @param cachedCounter
* The cachedCounter to set.
*/
public void setCachedCounter(int cachedCounter) {
this.cachedCounter = cachedCounter;
}
}


2. 自定义HotItemComparator

HotItemComparator实现了Comparator 接口, 实现的方法非常简单就是根据cachedCounter进行比较返回比较结果

正序:return obj1.getCachedCounter() - obj2.getCachedCounter();

倒序:return obj2.getCachedCounter() - obj1.getCachedCounter();




package com.cache;
import java.util.Comparator;
/**
* @author Weidong
*/
public final class HotItemComparator implements Comparator {
/*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object arg0, Object arg1) {
CacheObj obj1 = (CacheObj) arg0;
CacheObj obj2 = (CacheObj) arg1;
return obj1.getCachedCounter() - obj2.getCachedCounter();
}
}
3. 测试用例

定义变量:public static final Comparator HOT_ITEM = new HotItemComparator();
将HashMap追加到List对象sortList中:sortList.addAll(caches.values());
对sorList应用HOT_ITEM排序:Collections.sort(sortList, HOT_ITEM);


package com.cache;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author Weidong
*/
public class TestBean {
public static final Comparator HOT_ITEM = new HotItemComparator();

public static void sortMap() {
Map caches = new HashMap();
CacheObj s1 = new CacheObj();
s1.setCachedCounter(2);
CacheObj s2 = new CacheObj();
s2.setCachedCounter(3);
CacheObj s3 = new CacheObj();
s3.setCachedCounter(1);
caches.put("1", s1);
caches.put("2", s2);
caches.put("3", s3);

List sortList = new ArrayList();
sortList.addAll(caches.values());
Collections.sort(sortList, HOT_ITEM);
Iterator iter = sortList.iterator();
while (iter.hasNext()) {
CacheObj s = (CacheObj) iter.next();
System.out.println("counter is "+s.getCachedCounter());
}
}
public static void main(String[] args) {
sortMap();
}
}
输出:文中用正序

counter is 1
counter is 2
counter is 3



共1个网摘 [ 1 ] 

Tag/相关标签



    网站简介广告服务网站地图帮助联系方式诚聘英才English 问题报告
    北京创新乐知广告有限公司 版权所有 京 ICP 证 070598 号
    Copyright © 2000-2008, CSDN.NET, All Rights Reserved