CHAPTER 5 ArrayLists.

Slides:



Advertisements
Similar presentations
Chapter 22 Implementing lists: linked implementations.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Chapter 7 Iterators Modified. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using.
5-May-15 ArrayLists. 2 ArrayList s and arrays A ArrayList is like an array of Object s Differences between arrays and ArrayList s: Arrays have special.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
Chapter 3 Collection Classes Anshuman Razdan Department of Engineering
Lecture 221 CS110 Lecture 22 Tuesday, April 20, 2004 Announcements –hw10 due Thursday, April 22 –exam next Tuesday, April 27 Agenda –Questions –Error handling.
CHAPTER 6 Stacks Array Implementation. 2 Stacks A stack is a linear collection whose elements are added and removed from one end The last element to be.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
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.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Chapter 3 Introduction to Collections – Stacks Modified
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Chapter 6 Array-Based Lists.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
EECE 310: Software Engineering Iteration Abstraction.
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()
GENERICS. Generics  Classes and methods can have a type parameter (actually, more than one).  The type parameter can be any reference (class) type.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
RED-BLACK TREE SEARCH THE FOLLOWING METHOD IS IN TreeMap.java:
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
Chapter 4 Grouping Objects. Flexible Sized Collections  When writing a program, we often need to be able to group objects into collections  It is typical.
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
List Interface and Linked List Mrs. Furman March 25, 2010.
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:
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
1. What is it? It is a queue that access elements according to their importance value. Eg. A person with broken back should be treated before a person.
Iteration Abstraction SWE Software Construction Fall 2009.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
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.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
Reference Types CSE301 University of Sunderland Harry R Erwin, PhD.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
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.
slides adapted from Marty Stepp and Hélène Martin
CSC 243 – Java Programming, Spring, 2014 Week 4, Interfaces, Derived Classes, and Abstract Classes.
Iterators. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve.
Iterators.
Building Java Programs
Preconditions precondition: Something your method assumes is true at the start of its execution. Often documented as a comment on the method's header:
this keyword this : A reference to the implicit parameter Syntax:
this keyword this : A reference to the implicit parameter Syntax:
Lecture 2: Implementing ArrayIntList reading:
Programming in Java Lecture 11: ArrayList
slides created by Ethan Apter
Building Java Programs
slides created by Ethan Apter
Chapter 6 Array-Based Lists.
CSE 143 Lecture 4 More ArrayIntList:
Collections Framework
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Go to pollev.com/cse143.
Building Java Programs
Building Java Programs
Lecture 7: Linked List Basics reading: 16.2
slides created by Ethan Apter and Marty Stepp
CSC 205 Java Programming II
Presentation transcript:

CHAPTER 5 ArrayLists

FROM THE AbstractList CLASS: public boolean add(Object o) { add(size(), o); return true; } abstract public Object get(int index); public void add(int index, Object element) { throw new UnsupportedOperationException(); }

WHAT’S THE DIFFERENCE BETWEEN AN ABSTRACT METHOD AND A METHOD WHOSE DEFINITION THROWS AN EXCEPTION? ANY SUBCLASS OF AbstractList MUST DEFINE THE get METHOD IN ORDER TO BE INSTANTIABLE, BUT NEED NOT DEFINE THE TWO-PARAMETER add METHOD AS LONG AS THAT METHOD IS NOT INVOKED (AND THE ONE-PARAMETER add METHOD IS NOT INVOKED).

FIELDS IN THE ArrayList CLASS private transient Object[ ] elementData; // “transient” means that the array elementData need // not be saved if the ArrayList object is serialized. The // individual elements will be saved, but not the array. private int size;

// Postcondition: this ArrayList object has been initialized // to be empty and with a capacity given // by initialCapacity. public ArrayList (int initialCapacity) { elementData = new Object [initialCapacity]; } // constructor with int parameter

// Postcondition: this ArrayList object has been initialized // to be empty. public ArrayList ( ) { this (10); }

// Postcondition: o has been appended to this ArrayList // object and true has been returned. The // averageTime(n) is constant and // worstTime(n) is O (n). public boolean add (Object o) { ensureCapacity (size + 1); elementData [size++] = o; return true; }

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. }

public void ensureCapacity(int minCapacity) { modCount++; // discussed below int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData[] = elementData; int newCapacity = (oldCapacity * 3) / 2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; elementData = new Object[newCapacity]; System.arraycopy(oldData, 0, elementData, 0, size); }

public Object clone() { try { ArrayList v = (ArrayList)super.clone(); // copies size v.elementData = new Object[size]; System.arraycopy(elementData, 0, v.elementData, 0, size); v.modCount = 0; // the modCount field is // discussed later return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(); }

// Postcondition: this ArrayList has been initialized to a // copy of c. public ArrayList(Collection c) { this((c.size()*110)/100); // Allow 10% room for growth Iterator i = c.iterator( ); while (i.hasNext( )) elementData[size++] = i.next(); } NOTE: THIS IS CALLED THE COPY CONSTRUCTOR.

HERE ARE TWO WAYS TO CREATE A COPY OF myList : ArrayList newList = (ArrayList)myList.clone( ); ArrayList newList = new ArrayList (myList); SUPPOSE myList HAS 3 ELEMENTS:

Clone Copy Constructor A1 A2 A3 A1 A2 A3 null null null null null null null

ITERATORS – NOT NEEDED FOR ArrayList S for (int j = 0; j < myList.size( ); j++) gui.println (myList.get (j));

BUT ITERATORS ARE LEGAL: Iterator itr = myList.iterator( ); while (itr.hasNext( )) gui.println (itr.next( ));

INHERITED FROM AbstractList : protected transient int modCount = 0;

THE modCount FIELD IS INCREMENTED EVERY TIME THE ArrayList IS STRUCTURALLY MODIFIED, THAT IS, WITH AN INSERTION OR REMOVAL.

EACH ITERATOR CLASS IN THE JAVA COLLECTIONS FRAMEWORK HAS A FIELD: int expectedModCount = modCount;

public Object next( ) { … checkForComodification( );

final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); }

THE ITERATOR FAILS AS SOON AS IT IS DISCOVERED THAT ANOTHER OBJECT – EITHER ANOTHER ITERATOR OR THE ArrayList OBJECT ITSELF – HAS STRUCTURALLY MODIFIED THE ArrayList OBJECT.

FOR THAT REASON, ITERATORS IN THE JAVA COLLECTIONS FRAMEWORK ARE CALLED FAIL-FAST ITERATORS

FOR EXAMPLE, THE FOLLOWING CODE WILL THROW ConcurrentModificationException: public ModCountDriver( ) { ArrayList list = new ArrayList( ); list.add (“yes”); Iterator itr = list. iterator( ); list.add (“good”); itr.next( ); // exception thrown at this point } // default constructor

BASICALLY, ONCE YOU CONSTRUCT AN ITERATOR, YOU SHOULD NOT ADD OR REMOVE FROM THE COLLECTION EXCEPT THROUGH THE ITERATOR’S METHODS.

EXERCISE: WHAT ARE THE VALUES OF modCount AND expectedModCount WHEN THE next( ) METHOD IS CALLED IN THE ABOVE CONSTRUCTOR?

APPLICATION HIGH-PRECISION ARITHMETIC

IN PUBLIC-KEY CRYPTOGRAPHY, THE INTEGERS ARE HUNDREDS OF DIGITS LONG.

KEY FACTS: 1. TO GENERATE A VERY LONG INTEGER THAT IS PRIME, averageTime(n) IS O ((log n) 3 ). IF n = , (log 10 n) 3 = = 8,000,000.

2. TO FACTOR A VERY LONG INTEGER THAT IS NOT PRIME, averageTime(n) IS ABOUT n 1/ 2. IF n = , n 1/2 =

3. GIVEN PRIMES p AND q, (p – 1)(q – 1) IS USED TO ENCODE A PUBLIC MESSAGE.

4. TO DECODE THE MESSAGE, p AND q MUST BE KNOWN.

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.

// Postcondition: this VeryLongInt is empty. public VeryLongInt( ); // Precondition: the string s consists of a sequence of // characters, with non-digit characters // ignored. There are no leading zeroes, // except for 0 itself, which has a single '0'. // The worstTime (n) is O (n). // Postcondition: this VeryLongInt has been initialized // from s. public VeryLongInt (String s);

// Postcondition: a String representation of this // VeryLongInt has been returned. The // worstTime (n) is O (n). public String toString(); // Postcondition: This VeryLongInt has been // incremented by otherVeryLong. // The worstTime (n) is O (n). public void add (VeryLongInt otherVeryLong);

FOR EXAMPLE, THE FOLLOWING CODE CONSTRUCTS TWO VeryLongInt OBJECTS WITH VALUES 345 AND 6789 AND PRINTS OUT THEIR SUM.

VeryLongInt very1 = new VeryLongInt (“345”); VeryLongInt very2 = new VeryLongInt (“6789”); very1.add (very2); gui.println (very1); // = gui.println (very1.toString( ));

FIELDS AND METHOD DEFINITIONS FOR THE VeryLongInt CLASS THE ONLY FIELD IS: ArrayList digits; // holds all of the digits // in the VeryLongInt

public VeryLongInt( ) { final int INITIAL_CAPACITY = 500; digits = new ArrayList (INITIAL_CAPACITY); } // default constructor

public VeryLongInt (String s) { // FOR EACH CHARACTER c IN s, //IF ‘0’ <= c <= ‘9’ //APPEND (c – ‘0’) TO digits. } // constructor with string parameter SUPPOSE s = “3x79”. WHAT WILL digits CONTAIN?

public String toString( ) { final String EMPTY_STRING = ""; String s = EMPTY_STRING; for (int i = 0; i < digits.size(); i++) s += digits.get (i); return s; } // method toString

FOR THE add METHOD: VeryLongInt a1, a2; // a1 = {3, 8, 7, 4, 9, 8} // a2 = {5, 3, 6, 4} a1.add (a2);

LOOP 6 TIMES: 0: = 12 APPEND 2, AND THE CARRY IS 1. 1: (THE CARRY) = 16 APPEND 6 AND THE CARRY IS WE END UP WITH , SO REVERSE.

public void add (VeryLongInt otherVeryLong) { final int BASE = 10; int largerSize, partialSum, carry = 0; VeryLongInt sum = new VeryLongInt(); if (digits.size() > otherVeryLong.digits.size()) largerSize = digits.size(); else largerSize = otherVeryLong.digits.size();

for (int i = 0; i < largerSize; i++) { // Add the ith least significant digit in the // calling object, the ith least significant digit // in otherVeryLong, and the carry. // Append that sum % 10 to sum.digits // The new carry is that sum / 10. } // for if (carry == 1) sum.digits.add (new Integer (carry)); Collections.reverse (sum.digits); digits = sum.digits; } // method add

for (int i = 0; i < largerSize; i++) { partialSum = least (i) + otherVeryLong.least (i) + carry; sum.digits.add (new Integer ( partialSum % BASE)); carry = partialSum / BASE; } // for if (carry == 1) sum.digits.add (new Integer (carry)); Collections.reverse (sum.digits); digits = sum.digits; } // method add

SUPPOSE THE VeryLongInt OBJECT HAS THE VALUE THEN least (0) RETURNS 9 least (1) RETURNS 7 least (2) RETURNS 5 least (3) RETURNS 3 least (4) RETURNS 1 least (5) RETURNS 0

// Postcondition: If i >= digits.size(), 0 has been returned; // else the ith least significant digit in // digits has been returned. The rightmost // digit is the 0th least significant digit. private int least (int i) { if (i >= digits.size()) return 0; else return ((Integer)(digits.get ( digits.size() - i - 1))).intValue (); } // least

HOW LONG DOES THE add METHOD TAKE, ON AVERAGE? RECALL THAT n REFERS TO THE NUMBER OF 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);