Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 6 Array-Based Lists.

Similar presentations


Presentation on theme: "Chapter 6 Array-Based Lists."— Presentation transcript:

1 Chapter 6 Array-Based Lists

2 Chap.6 Contents 6.1 The List Interface 6.2 The ArrayList Class
6.2.1 Method Specifications for the ArrayList Class 6.2.2 A Simple Program with an ArrayList Object 6.2.3 The ArrayList Class’s Heading and Fields 6.2.4 Definition of the One-Parameter add Method 6.3 Application: High-Precision Arithmetic 6.3.1 Method Specifications of the VeryLongInt Class 6.3.2 Fields in the VeryLongInt Class 6.3.3 Method Definitions of the VeryLongInt Class

3 6.1 The List Interface

4 Boolean addAll( Collection<? Extends E> c) ;
That means that when addAll is called, the type of the argument’s elements can be any subclass of the actual class that replaced E when the calling object for the addAll method was instantiated. Boolean containsAll( collection<?> c) ; That means that type of the argument’s elements can be any class.

5

6

7

8 6.2 The ArrayList Class

9

10 6.2.1 Method Specifications for the ArrayList Class

11

12

13

14 6.2.2 A Simple Program with an ArrayList Object

15

16 converting s to int n

17 Constructs an ArrayList that holds up to n Double values
0. Constructs an ArrayList that holds up to n Double values. public ArrayList (int initialCapacity)

18 1. In a loop with i going from 0 to n – 1, appends i to the ArrayList
1. In a loop with i going from 0 to n – 1, appends i to the ArrayList. public boolean add (E element)

19 2. Inserts 1.4 at index n / 3. public void add (int index, E element)

20 3. Removes the element at index 2n / 3. public E remove (int index)

21 4. Multiplies the middle element by 3. 5
4. Multiplies the middle element by 3.5.public E get (int index) , public E set (int index, E element)

22 4. Multiplies the middle element by 3. 5
4. Multiplies the middle element by 3.5.public E get (int index) , public E set (int index, E element)

23 5. Prints out the ArrayList; public String toString()

24

25 6.2.3 The ArrayList Class’s Heading and Fields

26

27

28

29 ArrayList CLONE Example
class A { int a; String b; ArrayList c; public A( ){ a = 10; b = “hello”; c = new ArrayList(); c.add(“Yes”) ; } //end constructor } // end class A

30 複製 (clone) obj1 得到obj2 A obj2 =(A) obj1.clone() ;
10 100 hello helloworld Yes No

31 class Main(){ // obj2 複製 obj1
    public static void main(String[] args){ A obj1 = new A() ;      // 印出 obj1 System.out.println(obj1.a ) ;            System.out.println(obj1.b ) ;            System.out.println(obj1.c(0) ) ;  // 取ArrayList 第 0 個元素            /* obj2 複製 obj1 */ A obj2 =(A) obj1.clone() ;             // 設定obj2            obj2.a=100;  obj2.b=“helloworld”;            obj2.c.set(0, “No” ) ; //設定ArrayList 第 0 個元素為 “No”            // 印出 obj1 ,有受 obj2設定影響            System.out.println(obj1.a ) ;            System.out.println(obj1.b ) ;            System.out.println(obj1.c(0) ) ;  //取得ArrayList 第 0 個元素     }}

32 obj2 複製 obj1 10 hello Yes No // 因 obj1 & obj2 refer to 同一ArrayList
“Yes” is changed to “No” by obj2

33

34

35

36

37 Fields in ArrayList class
private transient E[ ] elementData; // “transient”: 如這ArrayList object 被 serialized, // array elementData 不會被儲存. // 但 個別的element會被儲存 private int size;

38 // ArrayList 初始化 ArrayList object 為具有
// 容量initialCapacity的空List. public ArrayList (int initialCapacity) {elementData = (E[ ]) new Object [initialCapacity];} // 有一個parameter 的constructor

39 // ArrayList 初始化 ArrayList object為具有
public ArrayList ( ) {this (10);}

40 6.2.4 Definition of the One-Parameter add Method
// add 增加 element 到這一個 ArrayList object // 然後傳回 true. // AverageTime(n) is constant; worstTime(n) is O (n). // public boolean add (E element) { ensureCapacity (size + 1); elementData [size++] = element; return true; }// add

41 public void ensureCapacity (int minCapacity) {
int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { {Increase the capacity by at least 50%, and copy the old array to the new array} } // ensureCapacity

42 to create a copy of myList called newList:
Here are two ways to create a copy of myList called newList: 這裡有2種產生myList 的copy (newList)的方式: 1. clone  ArrayList<String> newList = (ArrayList<String>) myList.clone( ); 2. copy constructor ArrayList<String> newList = new ArrayList<String> (myList); Suppose myList has 3 elements: A1,A2,A3.

43 (default constructor with capacity 10)
1. Clone A1 A2 A3 2. Copy Constructor (default constructor with capacity 10) A1 A2 A3 null null null null null null null A1 A2 A3 null null null null null null null

44 Iterators not needed for ArrayList,
as the code below without iterator is still pretty readable. for (int j = 0; j < myList.size( ); j++) System.out.println (myList.get (j));

45 But iterators are legal:
Iterator<Double> itr = myList.iterator( ); while (itr.hasNext( )) System.out.println (itr.next( ));

46 Even better: for (Double d : myList) System.out.println (d);

47 軟體達人 學藝記 本書有九個範例 (applications), 就像軟體博物館展出的九個著名作品, 你是初學者,站在名作面前,
軟體達人 學藝記 本書有九個範例 (applications), 就像軟體博物館展出的九個著名作品, 你是初學者,站在名作面前, 要用心凝神揣摩 大師 精巧而流暢 的創作手藝, 特別是 reuse high-level data structure 的功力 才能學成技藝,成為軟體達人! 下面是第一個範例:

48 6.3 Application: High-Precision Arithmetic
In public-key cryptography, the integers are hundreds of digits long.

49 Background on integers
short 16 bits min -32,768 (2**15) max 32,767 (2**15 -1) int 32 bits min -2,147,483,648 max 2,147,483,647 long 64 bits min -9,223,372,036,854,775,808 max 9,223,372,036,854,775,807

50 6.3.1 Method Specifications of the VeryLongInt Class
We will now develop a: VeryLongInt class to handle very long integers. In the method descriptions, n refers to the number of digits in the calling object. 我們將開發 class VeryLongInt class 來處理超長整數 在 method 描述, n 代表 calling object 中 digits 的位數.

51 /** VeryLongInt 以給予的String object s
* 來初始化 VeryLongInt object . * The worstTime(n) is O(n), * 這裡的 n 代表 s 的字元數目 * * @param s – 給予的 String object. * @throws NullPointerException – 如果 s 是 null. */ public VeryLongInt (String s)

52 /** toString 回傳 VeryLongInt 的 String.
* The worstTime(n) is O(n), * n 代表這個 VeryLongInt 的位數. * @return VeryLongInt 的 String */ public String toString()

53 /** * add 以參數 otherVeryLong 來加上 calling object. *
/** * add 以參數 otherVeryLong 來加上 calling object. * * worstTime(n) is O(n), * n 是在呼叫前 calling object * 和 otherVeryLong 二者較大者的位數 * @param otherVeryLong – 要被加到 calling object 的數 * @throws NullPointerException – * 如果 otherVeryLong 是空的 */ public void add (VeryLongInt otherVeryLong)

54 For example, the following code constructs two VeryLongInt objects
with values 345 and 6789 and prints out their sum. 例如下面的 程式以值 345 和 6789 來建構兩個 VeryLongInt 並印出兩數的和.

55 VeryLongInt very1 = new VeryLongInt ( “345”);
very1.add (very2); System.out.println (very1.toString ( ) );

56 8 test cases 無進位 = 357 = 357 有進位 largerSize 不變 = 7134 = 7134 有進位 largerSize +1 = 11110 除數字外,其餘符號皆略去 ?89 = 1245 7. 4* = 1245 超長整數 8. 9,223,372,036,854,775, ,223,372,036,854,775,808 = 18,446,744,073,709,551,616

57 6.3.2 Data Fields in the VeryLongInt Class
因此採用 ArrayList data structure 使它的每個 element 儲存 VeryLongInt 的一個數字 The only field (data structure) is: protected ArrayList<Integer> digits; // holds all of the digits in this VeryLongInt

58 6.3.3 Method Definitions of the VeryLongInt Class
public VeryLongInt (String s) { final char LOWEST_DIGIT_CHAR = '0'; digits = new ArrayList<Integer> (s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt (i); if(Character.isDigit(c)) // if “c” is not a digit, skip it. // append the integer to digits digits.add (c – LOWEST_DIGIT_CHAR); } //end for } // end VeryLongInt()

59 public String toString( )
{return digits.toString();}

60 For the add method of this class:
VeryLongInt a1, // a1 = {3, 8, 7, 4, 9, 8} a2; // a2 = {5, 3, 6, 4} a1.add (a2); /* 預期的和是 */

61 Loop 6 times to add: 0: = 12 (partialSum) Append 2, and the carry is 1. “jinwei” is not a good name. 1: (carry) = 16 Append 6 and the carry is 1. ... We end up with sumDigits , so reverse it to get digits of

62 public void add (VeryLongInt otherVeryLong) {
1) 決定 sumDigits 所需空間大小 (sumDigits 儲存 add 後結果,為一 ArrayList<integer>) 1.largerSize = 兩數的 digits.size() 取較大者 2.sumDigits 大小為 largerSize + 1 (test case 3) 2) 由右至左相加 (但迴圈由左至右執行 故須 least()抓最右的數) for i 從 0 到 largerSize-1 1.add 1) ith least significant digit in the calling object 2) ith least significant digit in otherVeryLong 3) carry to get partialSum 2.將 partialSum的個位數存入 sumDigits 3.將 partialSum的十位數存入 carry end for 3) 最後的 carry 若為 1,則將 carry 加到 sumDigits 4) Reverse sumDigits,存回 digits.

63 ith least significant digit:
protected int least (int i) Suppose the VeryLongInt object has the value Its size( ) is 5. Then: least (0) when i=0, return element at 4 (that is 9) least (1) when i=1 return element at 3 (that is 7) least (2) when i=2 return element at 2 (that is 5) least (3) when i=3 return element at 1 (that is 3) least (4) when i=4 return element at 0 (that is 1) least (5) when i=5 return From the above test cases, we figured out the source code: if (digits.size()-i-1) >= 0 return digits.size() – i – 1 else return 0

64 public void add (VeryLongInt otherVeryLong) {
final int BASE = 10;  //十進位基底為10 int largerSize, // 比較大的數的位數 partialSum, // 兩個digit 相加的和 carry = 0; // 兩個digit 相加的進位 // 1. 決定 sumDigits 所需空間大小 if (digits.size() > otherVeryLong.digits.size()) largerSize = digits.size(); else largerSize = otherVeryLong.digits.size(); ArrayList<Integer>sumDigits = new ArrayList<Integer>(largerSize + 1);

65 for (int i = 0; i < largerSize; i++) {
// 2. 加法由右至左相加 for (int i = 0; i < largerSize; i++) { // Add: 1) the ith least significant digit // in the calling object, //2) the ith least significant digit // in otherVeryLong, and //3) the carry to get partialSum // 將 partialSum 的個位數存入 sumDigits // add partialSum % to sumDigits; // 將 partialSum 的十位數存入 carry // partialSum / is carry. }  /*3*/if (carry == 1) sumDigits.add (carry); /*4*/Collections.reverse (sumDigits); digits = sumDigits; } // end of add

66 { partialSum = least (i) + otherVeryLong.least (i) + carry;
/*2*/ for (int i = 0; i < largerSize; i++) { partialSum = least (i) + otherVeryLong.least (i) + carry; carry = partialSum / BASE; sumDigits.add (partialSum % BASE);} /*3*/ if (carry == 1) sumDigits.add (carry); /*4*/ Collections.reverse (sumDigits); digits = sumDigits; } // end add()

67 /** least 回傳 digits中第 i 個最小有效字元
* (如 i 小於 digits.size()) 否則, 回傳 0 * * EX: digits是“13579” 當 i 是 0 則回傳 index 4 的 9 * 當 i 是1 則回傳 index 3 的 7 * @param i – 加法 for 迴圈的 index * 從最左邊(index 0)起 每次加一 右移一位 * @return - digits中第 i 個最小有效字元, * @throws IndexOutOfBoundsException – 如果 i 是負數. */ protected int least (int i) { if (i >= digits.size()) return 0; else return digits.get (digits.size() - i - 1); } // end of least

68 How long does the add method take, on average?
Recall that n refers to the number of digits. 回想 n 代表 digits 的位數

69

70 Exercise: For the following addition, show the final contents of
a1.digits.elementData: // a1 = {3, 8, 7, 4, 9, 8} // a2 = {5, 3, 6, 4} a1.add (a2); ANS: {3, 9, 2, 8, 6, 2}

71 Exercise: In the VeryLongInt class, define the size() method:
// Returns the number of digits // in this VeryLongInt object. public int size( ) ANS: public int size () { return digits.size();}


Download ppt "Chapter 6 Array-Based Lists."

Similar presentations


Ads by Google