1.创建一个Set集合,并用Set集合保存用户通过控制台输入的字符串。
1 import java.util.HashSet; 2 import java.util.Scanner; 3 4 public class Homework1 { 5 public static void main(String args[]) { 6 HashSet<String> arrSet = new HashSet<String>(); 7 Scanner sc = new Scanner(System.in); 8 while(sc.hasNextLine()) { 9 String a = sc.nextLine(); 10 if(a.equals("")) { 11 break; 12 } 13 arrSet.add(a); 14 } 15 sc.close(); 16 System.out.println(arrSet); 17 } 18 }
2. 创建一个List集合,添加10个元素。然后获取索引为5处的元素;再获取其中某2个元素的索引;再删除索引为3处的元素。
1 import java.util.ArrayList; 2 3 public class Homework2 { 4 public static void main(String args[]) { 5 String[] books = {"语1","数2","英3","物4","化5","生6","政7","史8","地9","选10"} ; 6 ArrayList<String> list = new ArrayList<String>(); 7 for (int i = 0; i < books.length; i++) { 8 list.add(books[i]); 9 } 10 System.out.println(list); 11 System.out.println(list.get(5)); 12 System.out.println(list.indexOf("数2")); 13 System.out.println(list.indexOf("选10")); 14 list.remove(3); 15 System.out.println(list); 16 } 17 }
3. 给定字符串数组,然后使用Map的key来保存数组中字符串元素,value保存该字符串元素的出现次数,最后统计出各字符串元素的出现次数。
1 import java.util.HashMap; 2 3 public class Homework3 { 4 public static int count(String[] str,String x) { 5 int temp = 0; 6 for (int i = 0; i < str.length; i++) { 7 if (str[i] == x) { 8 temp++; 9 } 10 } 11 return temp; 12 } 13 14 public static void main(String args[]) { 15 String[] str = {"a","b","a","b","c","a","b","c","b"}; 16 HashMap<String, Integer> hm = new HashMap<String, Integer>(); 17 for (int i = 0; i < str.length; i++) { 18 hm.put(str[i], 0); 19 } 20 System.out.println(hm); 21 hm.put("a", count(str,"a")); 22 hm.put("b", count(str,"b")); 23 hm.put("c", count(str,"c")); 24 System.out.println(hm); 25 } 26 }