六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 50|回复: 0

匿名类

[复制链接]

升级  66%

41

主题

41

主题

41

主题

秀才

Rank: 2

积分
149
 楼主| 发表于 2013-2-5 01:20:03 | 显示全部楼层 |阅读模式
package samples;import java.io.UnsupportedEncodingException;import java.util.ArrayList;import java.util.Collection;import java.util.Collections;import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeSet;public class TestCollections {public static void main(String[] args) throws UnsupportedEncodingException {Map<String, String> hm = new HashMap<String, String>();hm.put("1", "1");hm.put("2", "2");hm.put("3", "3");Set<String> hs = hm.keySet();List<String> l = new ArrayList<String>(hs);populate(hm, hs, l);Collections.reverse(l);populate(hm, hs, l);/* * error List<String> l2 = Collections.unmodifiableList(l); * l2.add("4"); *//* * Collections.sort() for List only *  * new Interface ()? 匿名类 */Collections.sort(l, new Comparator<String>() {public int compare(String s1, String s2) {return 1;}});Comparator<String> comparator = new Comparator<String>() {public int compare(String op1, String op2) {return 0;}};new String("Abc".toCharArray());new String("Abc".getBytes("UTF-8"), "UTF-8");/* * 构造了ts,按照自然排序 * 现在希望让ts按照另外一种方式排序,怎么做? * 下面ts2无效 */TreeSet<String> ts  = new TreeSet<String>();ts.add("1");ts.add("2");populateCollection(ts);TreeSet<String> ts2  = new TreeSet<String>(comparator);ts2=ts;populateCollection(ts);populateCollection(ts2);}public static void populateCollection(Collection<String> c) {for (String s : c) {System.out.print(s + " ");}System.out.println();}public static void populateMap(Map<String, String> c) {for (Map.Entry<String, String> entry : c.entrySet()) {System.out.print(entry.getKey() + " ");System.out.print(entry.getValue() + " ");}System.out.println();}public static void populate(Map<String, String> m, Set<String> s,List<String> l) {populateMap(m);populateCollection(s);populateCollection(l);System.out.println("==============================");}} 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表