本帖最后由 乔玉吉 于 2012-7-16 15:16 编辑
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.LinkedHashMap;
- import java.util.Map;
- import java.util.Set;
- import java.util.TreeMap;
- public class TreeMapSort {
- /**
- * 对TreeMap集合进行值排序,为什么new一个成员方法上的内部类会出错 而new一个匿名内部类和单独外部类而不出错
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- TreeMap<String, Integer> treeMap = new TreeMap<String, Integer>();
- treeMap.put("zhangsan", 28);
- treeMap.put("lisi", 18);
- treeMap.put("wangwu", 18);
- treeMap.put("wuxiao",9);
- Set<Map.Entry<String, Integer>> entrySet = treeMap.entrySet();
- ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String,Integer>>(treeMap.size());
- list.addAll(entrySet);
- Collections.sort(list,new myCompartor());//就这就编译报错,只不过new了一个成语方法上的内部类 ,new匿名内部类它就不报错,凭什么?
-
- //匿名内部类
- /*Collections.sort(list,new Comparator<Map.Entry<String, Integer>>(){
- @Override
- public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
- // TODO Auto-generated method stub
- return o1.getValue().compareTo(o2.getValue());
- }
- });*/
- Map<String, Integer> sortMap = new LinkedHashMap<String, Integer>();
- for(Map.Entry<String, Integer> entry:list){
- sortMap.put(entry.getKey(),entry.getValue());
- }
- Set<String> nameSet = sortMap.keySet();
- for(String name:nameSet){
- System.out.println(name+":"+sortMap.get(name));
- }
- }
- //成员上的内部类
- private final class myCompartor implements Comparator<Map.Entry<String, Integer>>{
- @Override
- public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
- // TODO Auto-generated method stub
- return o1.getValue().compareTo(o2.getValue());
- }
- }
- }
- //外部类
- /*class myCompartor implements Comparator<Map.Entry<String, Integer>>{
- @Override
- public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
- // TODO Auto-generated method stub
- return o1.getValue().compareTo(o2.getValue());
- }
- }*/
复制代码 |
|