馮志霞201771010107《面向物件程式設計(java)》第十一週學習總結
實驗十一 集合
實驗時間 2018-11-8
1、實驗目的與要求
(1) 掌握Vetor、Stack、Hashtable三個類的用途及常用API;
(2) 瞭解java集合框架體系組成;
(3) 掌握ArrayList、LinkList兩個類的用途及常用API。
(4) 瞭解HashSet類、TreeSet類的用途及常用API。
(5)瞭解HashMap、TreeMap兩個類的用途及常用API;
(6) 結對程式設計(Pair programming)練習,體驗程式開發中的兩人合作。
java中的Iterator功能比較簡單,並且只能單向移動:
(1) 使用方法iterator()要求容器返回一個Iterator。第一次呼叫Iterator的next()方法時,它返回序列的第一個元素。注意:iterator()方法是java.lang.Iterable介面,被Collection繼承。
(2) 使用next()獲得序列中的下一個元素。
(3) 使用hasNext()檢查序列中是否還有元素。
(4) 使用remove()將迭代器新返回的元素刪除。
HashSet的一些常用方法:
新增元素:
hashset.add(E e):返回boolean型,如果此 set 中尚未包含指定元素,則新增指定元素;如果此 set 已包含該元素,則該呼叫不更改 set 並返回
false。
刪除元素:
hashset.clear():從此 set 中移除所有元素。
hashset.remove(Object o):如果指定元素存在於此 set 中,則將其移除。
hashset.isEmpty():如果此 set 不包含任何元素,則返回
true。
hashset.contains(Object o):如果此 set 包含指定元素,則返回
true。
hashset.size():返回此 set 中的元素的數量(set 的容量)。
Set 介面繼承 Collection,但不允許重複,使用自己內部的一個排列機制。
List 介面繼承 Collection,允許重複,以元素安插的次序來放置元素,不會重新排列。
Map介面是一組成對的鍵-值物件,即所持有的是key-value pairs。Map中不能有重複的key。擁有自己的內部排列機制。
2、實驗內容和步驟
實驗1: 匯入第9章示例程式,測試程式並進行程式碼註釋。
測試程式1:
l 使用JDK命令執行編輯、執行以下三個示例程式,結合執行結果理解程式;
//示例程式1 import java.util.Vector; class Cat { private int catNumber; Cat(int i) { catNumber = i; } void print() { System.out.println("Cat #" + catNumber); } } class Dog { private int dogNumber; Dog(int i) { dogNumber = i; } void print() { System.out.println("Dog #" + dogNumber); } } public class CatsAndDogs { public static void main(String[] args) { Vector cats = new Vector();//建立向量類物件 for (int i = 0; i < 7; i++) cats.addElement(new Cat(i));//用向量類的API:addElement()新增元素 cats.addElement(new Dog(7));//新增第八個Dog類元素 for (int i = 0; i < cats.size()-1; i++)//此時cats的長度為8,而cat類物件只有7個 ((Cat) cats.elementAt(i)).print();//用向量類的API:elementAt(利用下表索引)找到元素 ((Dog) cats.elementAt(7)).print(); } }
//示例程式2 import java.util.*; public class Stacks { static String[] months = { "1", "2", "3", "4" }; public static void main(String[] args) { Stack stk = new Stack(); for (int i = 0; i < months.length; i++) stk.push(months[i]);//入棧 System.out.println(stk); System.out.println("element 2=" + stk.elementAt(2));//因為class Stack<E> extends Vector<E>所以可以使用elementAt來定位 while (!stk.empty()) System.out.println(stk.pop());//判斷如果棧不空,進行出棧操作(先進後出) } }
//示例程式3 import java.util.*; class Counter { int i = 1; public String toString() { return Integer.toString(i); } } public class Statistics { public static void main(String[] args) { Hashtable ht = new Hashtable(); for (int i = 0; i < 10000; i++) { Integer r = new Integer((int) (Math.random() * 20));//r此時為鍵值範圍(0~19) if (ht.containsKey(r)) ((Counter) ht.get(r)).i++;//得到相應的value else ht.put(r, new Counter());//如果鍵值不同則重新建立 } System.out.println(ht); } }
l 掌握Vetor、Stack、Hashtable三個類的用途及常用API。
Vector類類似長度可變的陣列,Vector中只能存放物件,Vector的元素通過下標進行訪問。
Stack類是Vector的子類,Stack類描述堆疊資料結構。
Hashtable用一個特殊的值來確定鍵,名為hashcode(雜湊碼)。所有物件都有一個雜湊碼,可以通過Object類的hashCode()方法獲得。
l 使用JDK命令編輯執行ArrayListDemo和LinkedListDemo兩個程式,結合程式執行結果理解程式;測試程式2:
import java.util.*;
public class ArrayListDemo {
public static void main(String[] argv) {
ArrayList al = new ArrayList();
al.add(new Integer(11));
al.add(new Integer(12));
al.add(new Integer(13));
al.add(new String("hello"));
//包裝類即使把基本型別變成物件型別 像ArrayList這樣的集合是不能儲存基本型別的只能儲存物件 為了方便這些集合的使用所以才有了把基本型別包裝成物件型別
System.out.println("Retrieving by index:");
for (int i = 0; i < al.size(); i++)
{
System.out.println("Element " + i + " = " + al.get(i));
}
}
}
import java.util.*; public class LinkedListDemo { public static void main(String[] argv) { LinkedList l = new LinkedList(); l.add(new Object()); l.add("Hello"); l.add("zhangsan"); ListIterator li = l.listIterator(0);//ListIterator<E> extends Iterator<E>迭代器 while (li.hasNext()) System.out.println(li.next()); if (l.indexOf("Hello") < 0) System.err.println("Lookup does not work"); else System.err.println("Lookup works"); } }
l 在Elipse環境下編輯執行除錯教材360頁程式9-1,結合程式執行結果理解程式;
l 掌握ArrayList、LinkList兩個類的用途及常用API。
package linkedList; import java.util.*; /** * This program demonstrates operations on linked lists. * @version 1.11 2012-01-26 * @author Cay Horstmann */ public class LinkedListTest { public static void main(String[] args) { List<String> a = new LinkedList<>(); a.add("Amy"); a.add("Carl"); a.add("Erica"); List<String> b = new LinkedList<>(); b.add("Bob"); b.add("Doug"); b.add("Frances"); b.add("Gloria"); // merge the words from b into a ListIterator<String> aIter = a.listIterator(); Iterator<String> bIter = b.iterator(); while (bIter.hasNext()) { if (aIter.hasNext()) aIter.next(); aIter.add(bIter.next());//將aIler和biter物件按其下表索引值依次遍歷 } System.out.println(a); // 從b裡面移除每一輪迴圈的第二個元素 bIter = b.iterator(); while (bIter.hasNext()) { bIter.next(); //跳過第一個元素 if (bIter.hasNext()) { bIter.next(); // skip next element bIter.remove(); // remove that element } } System.out.println(b);//此時b中元素只有兩個 a.removeAll(b);//從a裡面移除當前b中元素 System.out.println(a); } }
測試程式3:
l 執行SetDemo程式,結合執行結果理解程式;
import java.util.HashSet; import java.util.Iterator; public class SetDemo { public static void main(String[] argv) { HashSet h = new HashSet(); //也可以 Set h=new HashSet(),Hashset實現了Set介面 h.add("One"); h.add("Two"); h.add("Four"); h.add("Three"); Iterator it = h.iterator(); while (it.hasNext()) //hasnext檢查是否還有元素進行遍歷 { System.out.println(it.next()); } } }
l 在Elipse環境下除錯教材367頁-368程式9-3、9-4,結合程式執行結果理解程式;瞭解TreeSet類的用途及常用API。l 在Elipse環境下除錯教材365頁程式9-2,結合執行結果理解程式;瞭解HashSet類的用途及常用API。
package treeSet; import java.util.*; /** * An item with a description and a part number. */ public class Item implements Comparable<Item>//實現比較介面 { private String description; private int partNumber; /** * Constructs an item. * * @param aDescription * the item's description * @param aPartNumber * the item's part number */ public Item(String aDescription, int aPartNumber) { description = aDescription; partNumber = aPartNumber; } /** * Gets the description of this item. * * @return the description */ public String getDescription() { return description; } public String toString() { return "[description=" + description + ", partNumber=" + partNumber + "]"; } public boolean equals(Object otherObject) { if (this == otherObject) return true; if (otherObject == null) return false; if (getClass() != otherObject.getClass()) return false; Item other = (Item) otherObject; return Objects.equals(description, other.description) && partNumber == other.partNumber; } public int hashCode() { return Objects.hash(description, partNumber); } public int compareTo(Item other) { int diff = Integer.compare(partNumber, other.partNumber); return diff != 0 ? diff : description.compareTo(other.description); } }
package treeSet; import java.util.*; /** * This program sorts a set of item by comparing their descriptions. * @version 1.12 2015-06-21 * @author Cay Horstmann */ public class TreeSetTest { public static void main(String[] args) { SortedSet<Item> parts = new TreeSet<>(); parts.add(new Item("Toaster", 1234)); parts.add(new Item("Widget", 4562)); parts.add(new Item("Modem", 9912)); System.out.println(parts); NavigableSet<Item> sortByDescription = new TreeSet<>( Comparator.comparing(Item::getDescription));//吧自定義類物件放到Treeset排序 sortByDescription.addAll(parts); System.out.println(sortByDescription); } }
測試程式4:
l 使用JDK命令執行HashMapDemo程式,結合程式執行結果理解程式;
import java.util.*; public class HashMapDemo { public static void main(String[] argv) { HashMap h = new HashMap(); h.put("Adobe", "Mountain View, CA"); h.put("IBM", "White Plains, NY"); h.put("Sun", "Mountain View, CA"); String queryString = "IBM"; String resultString = (String) h.get(queryString);//get用來獲得value值(以鍵值為引數) System.out.println("They are located in: " + resultString); } }
l 瞭解HashMap、TreeMap兩個類的用途及常用API。l 在Elipse環境下除錯教材373頁程式9-6,結合程式執行結果理解程式;
package map; import java.util.*; /** * This program demonstrates the use of a map with key type String and value type Employee. * @version 1.12 2015-06-21 * @author Cay Horstmann */ public class MapTest { public static void main(String[] args) { Map<String, Employee> staff = new HashMap<>(); staff.put("144-25-5464", new Employee("Amy Lee")); staff.put("567-24-2546", new Employee("Harry Hacker")); staff.put("157-62-7935", new Employee("Gary Cooper")); staff.put("456-62-5527", new Employee("Francesca Cruz")); // 列印所有條目 System.out.println(staff); // 刪除一個專案 staff.remove("567-24-2546"); // replace an entry staff.put("456-62-5527", new Employee("Francesca Miller")); // 瀏覽一個值 System.out.println(staff.get("157-62-7935")); // 迭代遍歷 staff.forEach((k, v) -> System.out.println("key=" + k + ", value=" + v)); } }
實驗2:結對程式設計練習:
l 關於結對程式設計:以下圖片是一個結對程式設計場景:兩位學習夥伴坐在一起,面對著同一臺顯示器,使用著同一鍵盤,同一個滑鼠,他們一起思考問題,一起分析問題,一起編寫程式。
l 關於結對程式設計的闡述可參見以下連結:
http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html
http://en.wikipedia.org/wiki/Pair_programming
l 對於結對程式設計中程式碼設計規範的要求參考:
http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html
以下實驗,就讓我們來體驗一下結對程式設計的魅力。
l 確定本次實驗結對程式設計合作伙伴:孔維瀅
l 各自執行合作伙伴實驗九程式設計練習1,結合使用體驗對所執行程式提出完善建議;
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class Identify { private static ArrayList<Person> personlist; public static void main(String[] args) { personlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("E:\\身份證號.txt"); try { FileInputStream fis = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String temp = null; while ((temp = in.readLine()) != null) { Scanner linescanner = new Scanner(temp); linescanner.useDelimiter(" "); String name = linescanner.next(); String number = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String hometown = linescanner.nextLine(); Person person = new Person(); person.setName(name); person.setnumber(number); person.setsex(sex); int A = Integer.parseInt(age); person.setage(A); person.sethometown(hometown); personlist.add(person); } } catch (FileNotFoundException e) { System.out.println("身份資訊檔案找不到"); e.printStackTrace(); } catch (IOException e) { System.out.println("身份資訊檔案讀取錯誤"); e.printStackTrace(); } boolean isTrue = true; while (isTrue) { System.out.println("0.按姓名字典序輸出人員資訊;"); System.out.println("1.查詢最大年齡人員資訊;;"); System.out.println("2.查詢最小年齡人員資訊;"); System.out.println("3.尋找同鄉;"); System.out.println("4.尋找年齡相近的人;"); System.out.println("5.退出。"); String W = scanner.next(); switch(W) { case "0": Collections.sort(personlist); System.out.println(personlist.toString()); break; case "1": int a = 0; int j, c1 = 0, d1 = 0; for (int i = 1; i < personlist.size(); i++) { j = personlist.get(i).getage(); if (j > a) { a = j; c1 = i; } } System.out.println("年齡最大:" + personlist.get(c1)); break; case "2": int b = 100; int j1,c2 = 0,d2 = 0; for (int i = 1; i < personlist.size(); i++) { j1 = personlist.get(i).getage(); if (j1 < b) { b = j1; d2 = i; } } System.out.println("年齡最小:" + personlist.get(d2)); break; case "3": System.out.println("籍貫:"); String search = scanner.next(); String place = search.substring(0, 3); int i = 0; for (; i < personlist.size(); i++) { if (personlist.get(i).gethometown().substring(1, 4).equals(place)) System.out.println("你的同鄉是:" + personlist.get(i)); } break; case "4": System.out.println("年齡:"); int yourage = scanner.nextInt(); int nearaga = agenear(yourage); int value = yourage - personlist.get(nearaga).getage(); System.out.println("" + personlist.get(nearaga)); break; case "5": isTrue = false; System.out.println("退出程式!"); break; default: System.out.println("檢查輸入!"); } } } public static int agenear(int age) { int j = 0, b = 53, value = 0, c = 0; for (int i = 0; i < personlist.size(); i++) { value = personlist.get(i).getage() - age; if (value < 0) value = -value; if (value < b) { b = value; c = i; } } return c; } }
public class Person implements Comparable<Person> { private String name; private String number; private String sex; private int age; private String hometown; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getnumber() { return number; } public void setnumber(String number) { this.number = number; } public String getsex() { return sex; } public void setsex(String sex) { this.sex = sex; } public int getage() { return age; } public void setage(int age) { this.age = age; } public String gethometown() { return hometown; } public void sethometown(String hometown) { this.hometown = hometown; } public int compareTo(Person o) { return this.name.compareTo(o.getName()); } public String toString() { return name + " " + sex + " " + age + " " + number + " " + hometown + "\n"; } }
她對檔案的操作比我的更加簡潔明瞭,值得借鑑
l 各自執行合作伙伴實驗十程式設計練習2,結合使用體驗對所執行
package 計算器; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.Random; import java.util.Scanner; public class Studentexam { public static void main(String[] args) { Scanner in = new Scanner(System.in); Studentexam s = new Studentexam(); PrintWriter out = null; try { out = new PrintWriter("test.txt"); } catch (FileNotFoundException e) { System.out.println("檔案輸出失敗"); e.printStackTrace(); } int sum = 0; for (int i = 1; i <= 10; i++) { int a = (int) Math.round(Math.random() * 100); int b = (int) Math.round(Math.random() * 100); int m; Random rand = new Random(); m = (int) rand.nextInt(4) + 1; switch (m) { case 1: a = b + (int) Math.round(Math.random() * 100); while(b == 0){ b = (int) Math.round(Math.random() * 100); } while(a % b != 0){ a = (int) Math.round(Math.random() * 100); } System.out.println(a + "/" + b + "="); int c0 = in.nextInt(); out.println(a + "/" + b + "=" + c0); if (c0 == s.chufa(a, b)) { sum += 10; System.out.println("回答正確!"); } else { System.out.println("回答錯誤!"); } break; case 2: System.out.println(a + "*" + b + "="); int c = in.nextInt(); System.out.println(a + "*" + b + "=" + c); if (c == s.chengfa(a, b)) { sum += 10; System.out.println("回答正確!"); } else { System.out.println("回答錯誤!"); } break; case 3: System.out.println(a + "+" + b + "="); int c1 = in.nextInt(); out.println(a + "+" + b + "=" + c1); if (c1 == s.jiafa(a, b)) { sum += 10; System.out.println("回答正確!"); } else { System.out.println("回答錯誤!"); } break; case 4: while (a < b) { b = (int) Math.round(Math.random() * 100); } System.out.println(a + "-" + b + "="); int c2 = in.nextInt(); out.println(a + "-" + b + "=" + c2); if (c2 == s.jianfa(a, b)) { sum += 10; System.out.println("回答正確!"); } else { System.out.println("回答錯誤!"); } break; } } System.out.println("你的總成績為" + sum); out.println("你的總成績為" + sum); out.close(); } public int jiafa(int a,int b) { return a + b; } public int jianfa(int a, int b) { return a - b; } public int chengfa(int a, int b) { return a * b; } public int chufa(int a, int b) { if (b != 0 && a%b==0) return a / b; else return 0; } }
package 計算器; public class Student<T> { private T a; private T b; public Student() { a = null; b = null; } public Student(T a, T b) { this.a = a; this.b = b; } }
在執行她的這個實驗時,偶爾會出現只有九道題的情況,不知是麼原因
l 採用結對程式設計方式,與學習夥伴合作完成實驗九程式設計練習1;
import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Scanner; public class A{ private static ArrayList<Test> studentlist; public static void main(String[] args) { studentlist = new ArrayList<>(); Scanner scanner = new Scanner(System.in); File file = new File("D:\\身份證號.txt"); try { FileInputStream fis = new FileInputStream(file); BufferedReader in = new BufferedReader(new InputStreamReader(fis)); String temp = null; while ((temp = in.readLine()) != null) { Scanner linescanner = new Scanner(temp); linescanner.useDelimiter(" "); String name = linescanner.next(); String number = linescanner.next(); String sex = linescanner.next(); String age = linescanner.next(); String province =linescanner.nextLine(); Test student = new Test(); student.setName(name); student.setnumber(number); student.setsex(sex); int a = Integer.parseInt(age); student.setage(a); student.setprovince(province); studentlist.add(student); } } catch (FileNotFoundException e) { System.out.println("學生資訊檔案找不到"); e.printStackTrace(); } catch (IOException e) { System.out.println("學生資訊檔案讀取錯誤"); e.printStackTrace(); } boolean isTrue = true; while (isTrue) { System.out.println("1:字典排序"); System.out.println("2:輸出年齡最大和年齡最小的人"); System.out.println("3:尋找老鄉"); System.out.println("4:尋找年齡相近的人"); System.out.println("5:退出"); String m = scanner.next(); switch (m) { case "1": Collections.sort(studentlist); System.out.println(studentlist.toString()); break; case "2": int max=0,min=100; int j,k1 = 0,k2=0; for(int i=1;i<studentlist.size();i++) { j=studentlist.get(i).getage(); if(j>max) { max=j; k1=i; } if(j<min) { min=j; k2=i; } } System.out.println("年齡最大:"+studentlist.get(k1)); System.out.println("年齡最小:"+studentlist.get(k2)); break; case "3": System.out.println("province?"); String find = scanner.next(); String place=find.substring(0,3); for (int i = 0; i <studentlist.size(); i++) { if(studentlist.get(i).getprovince().substring(1,4).equals(place)) System.out.println("province"+studentlist.get(i)); } break; case "4": System.out.println("年齡:"); int yourage = scanner.nextInt(); int near=agematched(yourage); int value=yourage-studentlist.get(near).getage(); System.out.println(""+studentlist.get(near)); break; case "5": isTrue = false; System.out.println("退出程式!"); break; default: System.out.println("輸入有誤"); } } } public static int agematched(int age) { int j=0,min=53,value=0,k=0; for (int i = 0; i < studentlist.size(); i++) { value=studentlist.get(i).getage()-age; if(value<0) value=-value; if (value<min) { min=value; k=i; } } return k; } }
public class Test implements Comparable<Test> { private String name; private String number ; private String sex ; private int age; private String province; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getnumber() { return number; } public void setnumber(String number) { this.number = number; } public String getsex() { return sex ; } public void setsex(String sex ) { this.sex =sex ; } public int getage() { return age; } public void setage(int age) { this.age= age; } public String getprovince() { return province; } public void setprovince(String province) { this.province=province ; } public int compareTo(Test o) { return this.name.compareTo(o.getName()); } public String toString() { return name+"\t"+sex+"\t"+age+"\t"+number+"\t"+province+"\n"; } }
l 採用結對程式設計方式,與學習夥伴合作完成實驗十程式設計練習2。
import java.util.Random; import java.util.Scanner; import java.io.FileNotFoundException; import java.io.PrintWriter; public class Main{ public static void main(String[] args) { yunsuan counter=new yunsuan();//與其它類建立聯絡 PrintWriter out=null; try { out=new PrintWriter("D:/text.txt");//將檔案裡的內容讀入到D盤名叫text的檔案中 }catch(FileNotFoundException e) { System.out.println("檔案找不到"); e.printStackTrace(); } int sum=0; for(int i=0;i<10;i++) { int a=new Random().nextInt(100); int b=new Random().nextInt(100); Scanner in=new Scanner(System.in); //in.close(); switch((int)(Math.random()*4)) { case 0: System.out.println( ""+a+"+"+b+"="); int c1 = in.nextInt(); out.println(a+"+"+b+"="+c1); if (c1 == counter.plus(a, b)) { sum += 10; System.out.println("答案正確"); } else { System.out.println("答案錯誤"); } break ; case 1: if(a<b) { int temp=a; a=b; b=temp; }//為避免減數比被減數大的情況 System.out.println(""+a+"-"+b+"="); /*while((a-b)<0) { b = (int) Math.round(Math.random() * 100); }*/ int c2 = in.nextInt(); out.println(a+"-"+b+"="+c2); if (c2 == counter.minus(a, b)) { sum += 10; System.out.println("答案正確"); } else { System.out.println("答案錯誤"); } break ; case 2: System.out.println(""+a+"*"+b+"="); int c = in.nextInt(); out.println(a+"*"+b+"="+c); if (c == counter.multiply(a, b)) { sum += 10; System.out.println("答案正確"); } else { System.out.println("答案錯誤"); } break; case 3: while(b==0) { b = (int) Math.round(Math.random() * 100);//滿足分母不為0 } while(a%b!=0) { a = (int) Math.round(Math.random() * 100); b = (int) Math.round(Math.random() * 100); } System.out.println(""+a+"/"+b+"="); int c0= in.nextInt(); out.println(a+"/"+b+"="+c0); if (c0 == counter.divide(a, b)) { sum += 10; System.out.println("答案正確"); } else { System.out.println("答案錯誤"); } break; } } System.out.println("totlescore:"+sum); out.println(sum); out.close(); } }
public class yunsuan <T>{ private T a; private T b; public void yunsaun() { a=null; b=null; } public void yunsuan(T a,T b) { this.a=a; this.b=b; } public int plus(int a,int b) { return a+b; } public int minus(int a,int b) { return a-b; } public int multiply(int a,int b) { return a*b; } public int divide(int a,int b) { if(b!=0 && a%b==0) return a/b; else return 0; } }
總結:本次實驗和同伴一起程式設計,才發現思想不一樣得到問題的解決方式也不太一樣,我們不斷的找問題,找方法,體驗一起程式設計的過程還不錯,