java 代码
- package org.jh.app.count;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.List;
- import java.util.Set;
- import org.apache.commons.collections.Bag;
- import org.apache.commons.collections.BagUtils;
- import org.apache.commons.collections.bag.HashBag;
- public class CountSortTool {
- static public class Sort implements Comparable<Sort> {
- Object key;
- int num = 1;
- Sort(Object key) {
- this.key = key;
- }
- public Sort(Object o, int count) {
- this.key = o;
- num = count;
- }
- public String toString() {
- return key + ":" + num + "\n";
- }
- public boolean equals(Object obj) {
- System.out.println("equals");
- if (this == obj)
- return true;
- if (obj instanceof Sort) {
- Sort s = (Sort) obj;
- if (s.key.equals(s.key)) {
- num++;
- s.num++;
- return true;
- }
- }
- return false;
- }
- public Object getKey() {
- return key;
- }
- public void setKey(Object key) {
- this.key = key;
- }
- public int getNum() {
- return num;
- }
- public void setNum(int num) {
- this.num = num;
- }
- public int compareTo(Sort o) {
- return -num + o.num;
- }
- }
- public void push(String key) {
- bag.add(key);
- }
- Bag bag = BagUtils.typedBag(new HashBag(), String.class);
- public List<Sort> sort() {
- Set objs = bag.uniqueSet();
- List<Sort> listR = new ArrayList<Sort> ();
- for (Object o : objs) {
- listR.add(new Sort(o, bag.getCount(o)));
- }
- Collections.sort(listR);
- return listR;
- }
- }
本文介绍了一个使用Java实现的计数排序工具类。该工具利用Apache Commons Collections库中的Bag接口来收集并统计不同元素出现的次数,然后通过自定义的Sort类对这些元素进行排序。Sort类实现了Comparable接口,使得元素可以根据它们出现的频率进行比较。

被折叠的 条评论
为什么被折叠?



