Map 接口
Map方法举例
import java.util.*; public class TestMap2 { public static void main(String args[]) { Map<String, Integer> m1 = new HashMap<String , Integer>(); m1.put("one", 1); m1.put("two", 2); m1.put("three", 3); System.out.println(m1.size()); System.out.println(m1.containsKey("one")); if(m1.containsKey("two")) { //int i = ((Integer)m1.get("two")).intValue(); int i = m1.get("two"); System.out.println(i); } } }
TestMap2.java
import java.util.*; public class TestArgsWords { //private static final Integer ONE = new Integer(1); private static final int ONE = 1; public static void main(String args[]) { Map m = new HashMap(); for (int i = 0; i < args.length; i++) { //Integer freq = (Integer) m.get(args[i]); int freq = (Integer) m.get(args[i]) == null ? 0 : (Integer) m.get(args[i]); //m.put(args[i],(freq == null? ONE : new Integer(freq.intValue() + 1))); m.put(args[i], freq==0 ? ONE : freq + 1); } System.out.println (m.size() + " distinct words detected:"); System.out.println(m); } }
TestArgsWords
JDK1.5泛型
import java.util.*; public class BasicGeneric { public static void main(String[] args) { List<String> c = new ArrayList<String>(); c.add("aaa"); c.add("bbb"); c.add("ccc"); for(int i=0; i<c.size(); i++) { String s = c.get(i); System.out.println(s); } Collection<String> c2 = new HashSet<String>(); c2.add("aaa"); c2.add("bbb"); c2.add("ccc"); for(Iterator<String> it = c2.iterator(); it.hasNext(); ) { String s = it.next(); System.out.println(s); } } } class MyName implements Comparable<MyName> { int age; public int compareTo(MyName mn) { if(this.age > mn.age) return 1; else if(this.age < mn.age) return -1; else return 0; } }
BasicGeneric.java
import java.util.*; public class TestArgsWords2 { private static final int ONE = 1; public static void main(String args[]) { Map<String, Integer> m = new HashMap<String, Integer>(); for (int i = 0; i < args.length; i++) { if(!m.containsKey(args[i])) { m.put(args[i], ONE); } else { int freq = m.get(args[i]); m.put(args[i], freq + 1); } } System.out.println (m.size() + " distinct words detected:"); System.out.println(m); } }
TestArgsWords2.java
总结
时间: 2024-11-11 11:01:51