Chapter 6 Array-Based Lists.

Slides:



Advertisements
Similar presentations
Section 2.5 Single-Linked Lists. A linked list is useful for inserting and removing at arbitrary locations The ArrayList is limited because its add and.
Advertisements

The ArrayList Class and the enum Keyword
Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Building Java Programs
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 6 Array-Based Lists.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
CHAPTER 5 ArrayLists.
Textbook: Data Structures and the Java Collections Framework 3rd Edition by William Collins William Collins.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 15 Lecture 15-2: testing ArrayIntList; pre/post conditions and exceptions reading:
Aside: Running Supplied *.java Programs Just double clicking on a *.java file may not be too useful! 1.In Eclipse, create a project for this program or.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
1 CMPSCI 187 Computer Science 187 Introduction to Introduction to Programming with Data Structures Lecture 9 Doubly Linked Lists and Ordered Lists Lecture.
Implementing ArrayList Part T2 Lecture 6 School of Engineering and Computer Science, Victoria University of Wellington  Thomas Kuehne, Marcus Frean,
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
More on Arrays Review of Arrays of ints, doubles, chars
EKT472: Object Oriented Programming
Iterators.
Topic: Classes and Objects
Object-Oriented Concepts
The Class ArrayLinearList
Implementing ArrayList Part 1
List Representation - Array
Building Java Programs
Priority Queues.
Lecture 2: Implementing ArrayIntList reading:
null, true, and false are also reserved.
Programming in Java Lecture 11: ArrayList
Data Type (how to view it)
Introduction to Java Programming
Generics 27-Nov-18.
Words exercise Write code to read a file and display its words in reverse order. A solution that uses an array: String[] allWords = new String[1000]; int.
Chapter 8 Slides from GaddisText
Lecture 26: Advanced List Implementation
Chapter 10 ArrayList reading: 10.1
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Arrays of Objects Fall 2012 CS2302: Programming Principles.
Dynamic Data Structures and Generics
Fall 2018 CISC124 2/15/2019 CISC124 TA names and s will be added to the course web site by the end of the week. Labs start next week in JEFF 155:
Arrays and Array Lists CS 21a.
slides created by Ethan Apter
Code Refresher Test #1 Topics:
ArrayLists 22-Feb-19.
CS 200 Objects and ArrayList
JCF Collection classes and interfaces
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Winter 2019 CMPE212 4/7/2019 CMPE212 – Reminders
Java Programming Language
CSE 143 Lecture 2 ArrayIntList, binary search
Generics 2-May-19.
CSE 143 Lecture 4 Implementing ArrayIntList reading:
Objects with ArrayLists as Attributes
Part of the Collections Framework
CS 200 Objects and ArrayList
CSC 205 Java Programming II
Presentation transcript:

Chapter 6 Array-Based Lists

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

6.1 The List Interface

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.

6.2 The ArrayList Class

6.2.1 Method Specifications for the ArrayList Class

6.2.2 A Simple Program with an ArrayList Object

converting s to int n

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)

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)

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

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

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)

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)

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

6.2.3 The ArrayList Class’s Heading and Fields

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

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

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 個元素     }}

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

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

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

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

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

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

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.

(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

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

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

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

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

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

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

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 的位數.

/** 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)

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

/** * 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)

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

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

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

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

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

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

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); /* 預期的和是 392862 */

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

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.

ith least significant digit: protected int least (int i) Suppose the VeryLongInt object has the value 13579. 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 0 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

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

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 % 10 to sumDigits; // 將 partialSum 的十位數存入 carry // partialSum / 10 is carry. }  /*3*/if (carry == 1) sumDigits.add (carry); /*4*/Collections.reverse (sumDigits); digits = sumDigits; } // end of add

{ 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()

/** 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

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

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}

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