JAvaでのSet,Map,Stackの簡単な使い方
12650 ワード
1 import java.util.Iterator;
2 import java.util.Stack;
3 import java.io.*;
4 import java.util.Set;
5 import java.util.Map;
6 import java.util.HashMap;
7 import java.util.TreeSet;
8 public class StackUsing{
9 public static void main(String args[]) throws IOException{
10 Stack<Integer> s = new Stack<Integer>();
11 int i;
12 for(i=0; i<10; ++i)
13 s.push(i);
14
15 //it.hasNext() , true! it.next() ,
16 for(Iterator<Integer>it = s.iterator(); it.hasNext(); ){//
17 System.out.println(it.next());
18 }
19
20 for(Integer k:s){
21 System.out.println(k);
22 }
23
24 while(!s.empty()){//
25 System.out.println(s.pop());
26 }
27
28 Set<Integer> st = new TreeSet<Integer>();
29 for(i=0; i<10; ++i)
30 st.add(i);
31 for(Integer k: st){//
32 System.out.println(k);
33 }
34
35 for(Iterator<Integer>it = st.iterator(); it.hasNext(); ){//
36 System.out.println(it.next());
37 }
38
39 Set<myInteger> stp = new TreeSet<myInteger>();//
40 for(i=0; i<10; ++i)
41 stp.add(new myInteger(i, i*2));
42
43 for(myInteger x:stp){
44 System.out.println(x.first + " " + x.second);
45 }
46
47 Map<String, Integer>mp = new HashMap<String, Integer>();
48 String str;
49 BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
50
51 str=myInput.readLine();
52 while(str.compareTo("#")!=0){
53 Integer cnt=mp.get(str);
54 if(cnt==null)
55 cnt=new Integer(0);
56 ++cnt;
57 mp.put(str, cnt);
58 str=myInput.readLine();
59 }
60
61 ///3 Map
62 for(String ss : mp.keySet()){
63 System.out.println(ss + " " + mp.get(ss));
64 }
65 System.out.println("**********************");
66
67 // , ; ,
68 for(Map.Entry<String, Integer>entry : mp.entrySet()){// set 。 set Map.Entry
69 System.out.println(entry.getKey() + " " + entry.getValue());
70 }
71 System.out.println("**********************");
72
73 for(Iterator<Map.Entry<String, Integer> > it = mp.entrySet().iterator(); it.hasNext(); ){
74 Map.Entry<String, Integer>entry=it.next();
75 System.out.println(entry.getKey() + " " + entry.getValue());
76 }
77 }
78 }
79
80 class myInteger implements Comparable{
81 int first;
82 int second;
83 public myInteger(int a, int b){
84 first=a;
85 second=b;
86 }
87 public myInteger(){
88 first=0;
89 second=0;
90 }
91 public int compareTo(Object x){
92 if(first>((myInteger)x).first) return -1;//
93 else if(first==((myInteger)x).first) return 0;
94 else return 1;
95 }
96 }