HashMap和TreeMap是Map接口的两种实现,ArrayDeque和LinkedList是Queue接口的两种实现方式。下面的代码是我今天学习这四个数据结构之后写的。还是不熟悉,TreeMap中的其余构造方法我还没有实现,真搞不懂同样的数据结构用java却写的这么麻烦。。
package regexp;import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.Map; import java.util.NoSuchElementException; import java.util.Queue; import java.util.Set; import java.util.TreeMap;public class test {public static void main(String args[]) throws NoSuchElementException{//Queue接口的实现Queueq = new LinkedList (); //通过LinkedList实现Queue接口 // Queue q = new ArrayDeque //通过LinkedList实现Queue接口for(int i=0;i<10;i++) {q.add(i+1);}System.out.printf("%d%n", q.size());q.element();System.out.printf("%d%n", q.element());if(q.isEmpty()) {System.out.printf("%s%n", "The ArrayDeque is empty");} else {System.out.printf("%d%n", q.peek());}System.out.printf("%d%n", q.size());Integer first = q.remove(),last = q.remove();System.out.printf("%d %d%n",first,last);System.out.printf("%d%n", q.size());//Map接口的实现Map(); mp = new HashMap ();mp.put(1, "111");mp.put(2, "222");String tt = mp.put(3, "333");System.out.println(tt); //nullString tmp = mp.put(1, "444");System.out.printf("%s%n",tmp); //111System.out.printf("The size of the map is %d.%n", mp.size()); //3for(int i=0;i ) {System.out.printf("id=%d, value=%s%n",i+1,mp.get(i+1));}mp.remove(1); //delete key=1 Set keys = mp.keySet();//foreachfor(Integer num : keys) {System.out.printf(" %d", num);}//iteratorIterator it1 = keys.iterator();while(it1.hasNext()) {System.out.printf(" %d", it1.next());}Collection coll = mp.values();//foreachfor(String s : coll) {System.out.printf(" %s", s);}//iteratorIterator it2 = coll.iterator();while(it2.hasNext()) {System.out.printf(" %s", it2.next());}Set > ss = mp.entrySet();//foreachfor(Map.Entry pair : ss) {Integer num = pair.getKey();String value = pair.getValue();System.out.printf(" %s '+' id=%d, value=%s", pair,num,value);}//iteratorIterator > it3 = ss.iterator();while(it3.hasNext()) {System.out.printf(" %s", it3.next());}//TreeMapTreeMap treemp = new TreeMap (new myComparator());treemp.put(111,"111");treemp.put(222, "222");treemp.put(112,"112");treemp.put(113, "113");for(Map.Entry pair : treemp.entrySet()) {Integer num = pair.getKey();String str = pair.getValue();System.out.printf(" %d:%s ", num,str);}} }class myComparator implements Comparator {public myComparator() {}public int compare(Integer a,Integer b) {return a.compareTo(b);}}
下面是运行出来的结果,友友们可以对照着看,有没有初学者呀,come here and leave a message please!
10 1 1 10 1 2 8 null 111 The size of the map is 3. id=1, value=444 id=2, value=222 id=3, value=3332 3 2 3 222 333 222 333 2=222 '+' id=2, value=222 3=333 '+' id=3, value=333 2=222 3=333 111:111 112:112 113:113 222:222