1. 程式人生 > >201771010102 常惠琢 《2018面向物件程式設計(Java)》第11周學習總結

201771010102 常惠琢 《2018面向物件程式設計(Java)》第11周學習總結

實驗十一   集合

實驗時間 2018-11-8

1、實驗目的與要求

(1) 掌握VetorStackHashtable三個類的用途及常用API

(2) 瞭解java集合框架體系組成;

(3) 掌握ArrayListLinkList兩個類的用途及常用API

(4) 瞭解HashSet類、TreeSet類的用途及常用API

(5)瞭解HashMapTreeMap兩個類的用途及常用API

(6) 結對程式設計(Pair programming)練習,體驗程式開發中的兩人合作。

2、實驗內容和步驟

實驗1: 匯入第9章示例程式,測試程式並進行程式碼註釋。

測試程式1:

使用JDK命令執行編輯、執行以下三個示例程式,結合執行結果理解程式;

掌握Vetor、Stack、Hashtable三個類的用途及常用API。

//示例程式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));

        cats.addElement(new Dog(7));

        for (int i = 0; i < cats.size(); i++)

               ((Cat) cats.elementAt(i)).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));

      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));

                     if (ht.containsKey(r))

                            ((Counter) ht.get(r)).i++;

                     else

                            ht.put(r, new Counter());

              }

              System.out.println(ht);

       }

}

示例程式1:
 1 import java.util.Vector;
 2 
 3 public class CatsAndDogs {
 4     public static void main(String[] args) {
 5         Vector cats = new Vector();
 6         for (int i = 0; i < 7; i++)
 7             cats.addElement(new Cat(i));
 8         cats.addElement(new Dog(7));
 9         for (int i = 0; i < cats.size(); i++)
10             ((Cat) cats.elementAt(i)).print();
11     }
12 }
CatsAndDogs
 1 import java.util.Vector;
 2 
 3 class Cat {
 4     private int catNumber;
 5 
 6     Cat(int i) {
 7         catNumber = i;
 8     }
 9 
10     void print() {
11         System.out.println("Cat #" + catNumber);
12     }
13 }
Cat
 1 class Dog {
 2     private int dogNumber;
 3 
 4     Dog(int i) {
 5         dogNumber = i;
 6     }
 7 
 8     void print() {
 9         System.out.println("Dog #" + dogNumber);
10     }
11 }
Dog

                                                                                                                  

                                                                                                                   

                                                                                                                   

                                                                                                

示例程式1異常處理:

 1 import java.util.Vector;
 2 
 3 class Cat {
 4     private int catNumber;
 5 
 6     Cat(int i) {
 7         catNumber = i;
 8     }
 9 
10     void print() {
11         System.out.println("Cat #" + catNumber);
12     }
13 }
14 
15 class Dog {
16     private int dogNumber;
17 
18     Dog(int i) {
19         dogNumber = i;
20     }
21 
22     void print() {
23         System.out.println("Dog #" + dogNumber);
24     }
25 }
26 
27 public class CatsAndDogs {
28     public static void main(String[] args) {
29         Vector cats = new Vector();
30         for (int i = 0; i < 7; i++)
31             cats.addElement(new Cat(i));
32         cats.addElement(new Dog(7));
33         for (int i = 0; i < cats.size(); i++)
34             if (cats.elementAt(i) instanceof Cat) {
35                 ((Cat) cats.elementAt(i)).print();
36             }
37             else {
38                 ((Dog) cats.elementAt(i)).print();
39             }
40     }
41 }
CatsAndDogs 

                                                                                      

                                                                                                              

 

 

示例程式2:

 1 import java.util.*;
 2 
 3 public class Stacks {
 4     static String[] months = { "1", "2", "3", "4" };
 5 
 6     public static void main(String[] args) {
 7         Stack stk = new Stack();
 8         for (int i = 0; i < months.length; i++)
 9             stk.push(months[i]);
10         System.out.println(stk);
11         System.out.println("element 2=" + stk.elementAt(2));
12         while (!stk.empty())
13             System.out.println(stk.pop());
14     }
15 }
Stacks

                                                                                                      

                                                                                                                   

 1 import java.util.Hashtable;
 2 
 3 public class Statistics {
 4     public static void main(String[] args) {
 5         Hashtable ht = new Hashtable();
 6         for (int i = 0; i < 10000; i++) {
 7             Integer r = new Integer((int) (Math.random() * 20));
 8             if (ht.containsKey(r))
 9                 ((Counter) ht.get(r)).i++;
10             else
11                 ht.put(r, new Counter());
12         }
13         System.out.println(ht);
14     }
15 }
Statistics
1 import java.util.*;
2 
3 class Counter {
4     int i = 1;
5 
6     public String toString() {
7         return Integer.toString(i);
8     }
9 }
Counter
 1 import java.util.*;
 2 
 3 class Counter {
 4     int i = 1;//i未加訪問許可權修飾符。許可權修飾符共有四種許可權修飾符,分別是public,protected,預設和private。
 5 
 6     public String toString() {
 7         return Integer.toString(i);
 8     }
 9 }
10 
11 public class Statistics {
12     public static void main(String[] args) {
13         Hashtable ht = new Hashtable(); //建立了一個雜湊表類物件
14         for (int i = 0; i < 10000; i++) {
15             Integer r = new Integer((int) (Math.random() * 20)); //生成20個整型隨機數
16             if (ht.containsKey(r))//通過ht呼叫containsKey的方法
17                 ((Counter) ht.get(r)).i++;//通過Counter類物件引用i的屬性
18             else
19                 ht.put(r, new Counter());//生成了一個Counter類物件,屬性值為初始值。
20         }
21         System.out.println(ht);
22     }
23 }
Statistics

 

                                                                                                          

                                                                                                                     

     

測試程式2:

使用JDK命令編輯執行ArrayListDemo和LinkedListDemo兩個程式,結合程式執行結果理解程式;

import java.util.*;

 

public class ArrayListDemo {

public static void main(String[] argv) {

        ArrayList al = new ArrayList();

        // Add lots of elements to the ArrayList...

        al.add(new Integer(11));

        al.add(new Integer(12));

        al.add(new Integer(13));

        al.add(new String("hello"));

        // First print them out using a for loop.

        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);

        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");

   }

}

 1 import java.util.*;
 2 
 3 public class ArrayListDemo {
 4     public static void main(String[] argv) {
 5         ArrayList al = new ArrayList();
 6         // 向ARARYLIST中新增大量元素。
 7         al.add(new Integer(11));
 8         al.add(new Integer(12));
 9         al.add(new Integer(13));
10         al.add(new String("hello"));
11         // 首先用一個for迴圈打印出來。
12         System.out.println("Retrieving by index:");
13         for (int i = 0; i < al.size(); i++) {
14             System.out.println("Element " + i + " = " + al.get(i));
15         }
16     }
17 }
ArrayListDemo
 1 import java.util.*;
 2 public class LinkedListDemo {
 3     public static void main(String[] argv) {
 4         LinkedList l = new LinkedList();
 5         l.add(new Object());
 6         l.add("Hello");
 7         l.add("zhangsan");
 8         ListIterator li = l.listIterator(0);
 9         while (li.hasNext())
10             System.out.println(li.next());
11         if (l.indexOf("Hello") < 0)   
12             System.err.println("Lookup does not work");
13         else
14             System.err.println("Lookup works");
15    }
16 }
LinkedListDemo

                                                                                                                                                                                                                                                                            

                                                                                                                  

                                                                                                                           

 1 import java.util.*;
 2 
 3 public class ArrayListDemo {
 4     public static void main(String[] argv) {
 5         ArrayList al = new ArrayList();
 6         // 向ARARYLIST中新增大量元素。
 7         al.add(new Integer(11));
 8         al.add(new Integer(12));
 9         al.add(new Integer(13));
10         al.add(new String("hello"));//集合中的元素可以是不同類物件
11         System.out.println(al.size());
12         // 首先用一個for迴圈打印出來。
13         System.out.println("Retrieving by index:");
14         for (int i = 0; i < al.size(); i++) {
15             System.out.println("Element " + i + " = " + al.get(i));
16         }
17     }
18 }
ArrayListDemo

                                                                

                                                                                                                                          

 1 import java.util.*;
 2 public class LinkedListDemo {
 3     public static void main(String[] argv) {
 4         LinkedList l = new LinkedList();
 5         l.add(new Object());
 6         l.add("Hello");
 7         l.add("zhangsan");
 8         ListIterator li = l.listIterator(0);
 9         while (li.hasNext())
10             System.out.println(li.next());
11         if (l.indexOf("Hello") < 0)   //是否為l中的索引值
12             System.err.println("Lookup does not work");
13         else
14             System.err.println("Lookup works");
15    }
16 }
LinkedListDemo

在Elipse環境下編輯執行除錯教材360頁程式9-1,結合程式執行結果理解程式;

掌握ArrayList、LinkList兩個類的用途及常用API。

 1 package linkedList;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  * 這個程式演示了連結串列上的操作 
 7  * @version 1.11 2012-01-26
 8  * @author Cay Horstmann
 9  */
10 public class LinkedListTest
11 {
12    public static void main(String[] args)
13    {
14       List<String> a = new LinkedList<>();
15       a.add("Amy");
16       a.add("Carl");
17       a.add("Erica");
18 
19       List<String> b = new LinkedList<>();
20       b.add("Bob");
21       b.add("Doug");
22       b.add("Frances");
23       b.add("Gloria");
24 
25       //將單詞從B合併為A 
26 
27       ListIterator<String> aIter = a.listIterator();
28       Iterator<String> bIter = b.iterator();
29 
30       while (bIter.hasNext())
31       {
32          if (aIter.hasNext()) aIter.next();
33          aIter.add(bIter.next());
34       }
35 
36       System.out.println(a);
37 
38       // remove every second word from b
39 
40       bIter = b.iterator();
41       while (bIter.hasNext())
42       {
43          bIter.next(); // 跳過一個元素
44          if (bIter.hasNext())
45          {
46             bIter.next(); // 跳過下一元素 
47             bIter.remove(); // 刪除該元素 
48          }
49       }
50 
51       System.out.println(b);
52 
53       //批量操作:從A中刪除B中的所有單詞 
54 
55       a.removeAll(b);
56 
57       System.out.println(a);
58    }
59 }
View Code

                                                                                                   

                                                    

測試程式3:

執行SetDemo程式,結合執行結果理解程式;

import java.util.*;

public class SetDemo {

    public static void main(String[] argv) {

        HashSet h = new HashSet(); //也可以 Set h=new HashSet()

        h.add("One");

        h.add("Two");

        h.add("One"); // DUPLICATE

        h.add("Three");

        Iterator it = h.iterator();

        while (it.hasNext()) {

             System.out.println(it.next());

        }

    }

}

 1 import java.util.HashSet;
 2 import java.util.Iterator;
 3 public class SetDemo {
 4     public static void main(String[] argv) {
 5         HashSet h = new HashSet(); //也可以 Set h=new HashSet()
 6         h.add("One");
 7         h.add("Two");
 8         h.add("One"); // DUPLICATE   重複; 複製; 影印; 列印;
 9         h.add("Three");
10         Iterator it = h.iterator();
11         while (it.hasNext()) {
12              System.out.println(it.next());
13         }
14     }
15 }
SetDemo

                                                                                                             

                                                   

在Elipse環境下除錯教材365頁程式9-2,結合執行結果理解程式;瞭解HashSet類的用途及常用API。

 1 package set;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  *這個程式使用一個集合來列印System.in中所有唯一的單詞
 7  * @version 1.12 2015-06-21
 8  * @author Cay Horstmann
 9  */
10 public class SetTest
11 {
12    public static void main(String[] args)
13    {
14       Set<String> words = new HashSet<>(); //雜湊集實現集
15       long totalTime = 0;
16 
17       try (Scanner in = new Scanner(System.in))
18       {
19          while (in.hasNext())
20          {
21             String word = in.next();
22             long callTime = System.currentTimeMillis();
23             words.add(word);
24             callTime = System.currentTimeMillis() - callTime;
25             totalTime += callTime;
26          }
27       }
28 
29       Iterator<String> iter = words.iterator();
30       for (int i = 1; i <= 20 && iter.hasNext(); i++)
31          System.out.println(iter.next());
32       System.out.println(". . .");
33       System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds.");
34    }
35 }
SetTest

                                                                                           

                                         

 

在Elipse環境下除錯教材367頁-368程式9-3、9-4,結合程式執行結果理解程式;瞭解TreeSet類的用途及常用API。

 1 import java.util.*;
 2 
 3 /**
 4  * 該程式通過比較它們的描述對一組專案進行排序。
 5  * @version 1.12 2015-06-21
 6  * @author Cay Horstmann
 7  */
 8 public class TreeSetTest
 9 {
10    public static void main(String[] args)
11    {
12       SortedSet<Item> parts = new TreeSet<>();
13       parts.add(new Item("Toaster", 1234));
14       parts.add(new Item("Widget", 4562));
15       parts.add(new Item("Modem", 9912));
16       System.out.println(parts);
17 
18       NavigableSet<Item> sortByDescription = new TreeSet<>(
19             Comparator.comparing(Item::getDescription));
20 
21       sortByDescription.addAll(parts);
22       System.out.println(sortByDescription);
23    }
24 }
TreeSetTest
 1 package treeSet;
 2 
 3 import java.util.*;
 4 
 5 /**
 6  * 具有描述和零件編號的專案
 7  */
 8 public class Item implements Comparable<Item>
 9 {
10    private String description;
11    private int partNumber;
12 
13    /**
14     * 構造一個專案
15     * 
16     * @param aDescription
17     *           the item's description
18     * @param aPartNumber
19     *           the item's part number
20     */
21    public Item(String aDescription, int aPartNumber)
22    {
23       description = aDescription;
24       partNumber = aPartNumber;
25    }
26 
27    /**
28     * 獲取此項的說明。
29     * 
30     * @返回描述 
31     */
32    public String getDescription()
33    {
34       return description;
35    }
36 
37    public String toString()
38    {
39       return "[description=" + description + ", partNumber=" + partNumber + "]";
40    }
41 
42    public boolean equals(Object otherObject)
43    {
44       if (this == otherObject) return true;
45       if (otherObject == null) return false;
46       if (getClass() != otherObject.getClass()) return false;
47       Item other = (Item) otherObject;
48       return Objects.equals(description, other.description) && partNumber == other.partNumber;
49    }
50 
51    public int hashCode()
52    {
53       return Objects.hash(description, partNumber);
54    }
55 
56    public int compareTo(Item other)
57    {
58       int diff = Integer.compare(partNumber, other.partNumber);
59       return diff != 0 ? diff : description.compareTo(other.description);
60    }
61 }
Item

                                                                                                           

                                                                                                           

                                                                           

測試程式4:

使用JDK命令執行HashMapDemo程式,結合程式執行結果理解程式;

import java.util.*;

public class HashMapDemo {

   public static void main(String[] argv) {

      HashMap h = new HashMap();

      // The hash maps from company name to address.

      h.put("Adobe", "Mountain View, CA");

      h.put("IBM", "White Plains, NY");

      h.put("Sun", "Mountain View, CA");

      String queryString = "Adobe";

      String resultString = (String)h.get(queryString);

      System.out.println("They are located in: " +  resultString);

  }

}

 1 import java.util.*;
 2 public class HashMapDemo {
 3    public static void main(String[] argv) {
 4       HashMap h = new HashMap();
 5       // 從公司名稱到地址的雜湊對映。
 6       h.put("Adobe", "Mountain View, CA");
 7       h.put("IBM", "White Plains, NY");
 8       h.put("Sun", "Mountain View, CA");
 9       String queryString = "Adobe";
10       String resultString = (String)h.get(queryString);
11       System.out.println("They are located in: " +  resultString);
12   }
13 }
HashMapDemo

                                                                                   

                &n