匿名类

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("==============================");
	}
}

 

你可能感兴趣的:(java,C++,c,C#)