標籤:知識 new style input shm ring his color buffer
1.建立一個Set集合,儲存使用者輸入的資料
1 package test; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.util.ArrayList; 7 import java.util.HashMap; 8 import java.util.HashSet; 9 import java.util.Iterator;10 import java.util.LinkedHashSet;11 import java.util.List;12 import java.util.Map;13 import java.util.Set;14 15 class A {16 public int count;17 public A(int count) {18 this.count = count;19 }20 21 public boolean equals(Object obj){22 if (this == obj) {23 return true;24 }25 if (obj != null && obj.getClass() == A.class) {26 A r = (A)obj;27 return r.count == this.count;28 }29 return false;30 }31 32 public int hashCode() {33 return this.count;34 }35 36 public String toString() {37 return this.count+"";38 }39 40 }41 public class TestCollection {42 public static void testSet() throws Exception {43 //Set set = new LinkedHashSet();44 //Set set = new TreeSet();45 Set set = new HashSet();46 int keyIn;47 int num = 0;48 49 while ( num++ < 2) {50 //Scanner sc = new Scanner(System.in);51 //keyIn = sc.nextInt();52 BufferedReader br = new BufferedReader(new InputStreamReader(System.in));53 keyIn = Integer.parseInt(br.readLine());54 set.add(new A(keyIn));55 }56 System.out.println(set);57 }58 59 public static void testList() {60 List list = new ArrayList();61 for (int i=0; i<10; i++) {62 list.add(new A(i));63 }64 System.out.println(list);65 }66 67 public static void testMap() {68 String[] str = new String[] {"a","b","a","b","c","a","b","c"};69 Map<String, Integer> map = new HashMap();70 Set<String> set = new LinkedHashSet();71 for (int i = 0; i < str.length; i++) {72 set.add(str[i]);73 }74 75 76 String key;77 Iterator it = set.iterator();78 while (it.hasNext()) {79 int val = 0;80 key = (String)it.next();81 for (int i = 0; i < str.length; i++) {82 if (str[i] == key) val++;83 }84 map.put(key, val);85 }86 87 System.out.println(map);88 }89 90 public static void main(String[] args) throws Exception {91 //TestCollection.testSet();92 //TestCollection.testList();93 TestCollection.testMap();94 }95 }
JAVA基礎知識之JVM-——集合練習