Chapter 6 Array-Based Lists.

Slides:



Advertisements
Similar presentations
The List ADT Textbook Sections
Advertisements

Topic 9 The Queue ADT.
Chapter 5 Queues Modified. Chapter Scope Queue processing Comparing queue implementations 5 - 2Java Software Structures, 4th Edition, Lewis/Chase.
Chapter 14 Queues. Chapter Scope Queue processing Using queues to solve problems Various queue implementations Comparing queue implementations Java Foundations,
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.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Chapter 3 Collection Classes Anshuman Razdan Department of Engineering
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
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.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
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.
Chapter 14 Queues. First a Review Queue processing Using queues to solve problems – Optimizing customer service simulation – Ceasar ciphers – Palindrome.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
04/29/ Introduction to Vectors?... A vector is a dynamic array. - It can be expanded and shrunk as required - A Component of a vector can be accessed.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
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.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
(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:
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 5: Queues Java Software Structures: Designing and Using Data.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
CS 367 Introduction to Data Structures Lecture 2 Audio for Lecture 1 is available Homework 1 due Friday, September 18.
Print Me Who’s Data? First Executed Name Me My Mistake Q $100 Q $200 Q $300 Q $400 Q $500 Q $100 Q $200 Q $300 Q $400 Q $500 Final Jeopardy.
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:
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.
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
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.
Arrays and Array Lists CS 21a. Problem 1: Reversing Input Problem: Read in three numbers and then print out the numbers in reverse order Straightforward.
The ArrayList Data Structure The Most Important Things to Review.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Recursive Objects  an object that holds a reference to its own type is a recursive object  linked lists and trees are classic examples in computer science.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 6 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
Iterators. Chapter Scope The purpose of an iterator The Iterator and Interable interfaces The concept of fail-fast collections Using iterators to solve.
The Queue ADT.
Iterators.
Object-Oriented Concepts
The List ADT Reading: Textbook Sections 3.1 – 3.5
The Class ArrayLinearList
Preconditions precondition: Something your method assumes is true at the start of its execution. Often documented as a comment on the method's header:
Chapter 7 Iterators.
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
The List ADT Reading: Textbook Sections 3.1 – 3.5
Dynamic Data Structures and Generics
Chapter 6 Array-Based Lists.
ArrayLists 22-Feb-19.
Heaps and Priority Queues
Recursive Objects Singly Linked Lists.
CSC 205 Java Programming II
Presentation transcript:

Chapter 6 Array-Based Lists

Fields in the ArrayList class private transient E[ ] 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;

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

// Initializes this ArrayList object to be empty. public ArrayList ( ) { this (10); }

// Appends element to this ArrayList object and // returns true. The averageTime(n) is constant and // worstTime(n) is O (n). public boolean add (E element) { ensureCapacity (size + 1); elementData [size++] = element; 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++; // See Appendix 2 int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { E oldData[] = elementData; int newCapacity = (oldCapacity * 3) / 2 + 1; if (newCapacity < minCapacity) newCapacity = minCapacity; elementData = (E[ ]) new Object[newCapacity]; System.arraycopy(oldData, 0, elementData, 0, size); }

// Initializes this ArrayList to a copy of c. public ArrayList(Collection c) { size = c.size(); // Allow 10% room for growth elementData = (E[])new Object[(int)Math.min( (size*110L)/100,Integer.MAX_VALUE)]; c.toArray(elementData); } Note: This is called the copy constructor.

Iterators – not needed for ArrayList S for (int j = 0; j < myList.size( ); j++) System.out.println (myList.get (j));

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

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

Application High-Precision Arithmetic

In public-key cryptography, the integers are hundreds of digits long.

3. Given primes p and q, pq 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.

/** Initializes this VeryLongInt object from a given String * object. The worstTime(n) is O(n), where n represents * the number of characters in s. * s – the given String object. * NullPointerException – if s is null. * */ public VeryLongInt (String s)

/** * Returns a String representation of this VeryLongInt * object. The worstTime(n) is O(n), where n represents * the number of digits in this VeryLongInt object. * a String representation of this VeryLongInt * object: [highest digit, next highest digit, …]. * */ public String toString()

/** * Increments this VeryLongInt object by a specified * VeryLongInt object. * The worstTime(n) is O(n), where n is the number of * digits in the larger of this VeryLongInt object (before the * call) and the specified VeryLongInt object. * otherVeryLong – the specified VeryLongInt * object to be added to this VeryLongInt object. * NullPointerException – if otherVeryLong is * null * */ 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); System.out.println (very1); // = System.out.println // (very1.toString( ));

Fields and method definitions for the VeryLongInt class The only field is: protected ArrayList digits; // holds all of the // digits in this VeryLongInt

public VeryLongInt (String s) { final char LOWEST_DIGIT_CHAR = '0'; digits = new ArrayList (s.length()); for (int i = 0; i < s.length(); i++) { char c = s.charAt (i); if (Character.isDigit(c)) digits.add (c – LOWEST_DIGIT_CHAR); } // for } // constructor with string parameter

public String toString( ) { return digits.toString(); } // 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; if (digits.size() > otherVeryLong.digits.size()) largerSize = digits.size(); else largerSize = otherVeryLong.digits.size(); ArrayList sumDigits = new ArrayList (largerSize + 1);

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 sumDigits // The new carry is that sum / 10. } // for if (carry == 1) sumDigits.add (carry); Collections.reverse (sumDigits); digits = sumDigits; } // method add

for (int i = 0; i < largerSize; i++) { partialSum = least (i) + otherVeryLong.least (i) + carry; carry = partialSum / BASE; sumDigits.add (partialSum % BASE); } // for if (carry == 1) sumDigits.add (carry); Collections.reverse (sumDigits); digits = sumDigits; } // 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

/** Returns the ith least significant digit in digits if i is a non- * negative int less than digits.size(). Otherwise, returns 0. * i – the number of positions from the right-most digit in * digits to the digit sought. * ith least significant digit in digits, or 0 if no such digit. * IndexOutOfBoundsException – if i is negative. * */ protected int least (int i) { if (i >= digits.size()) return 0; return digits.get (digits.size() - i - 1); } // least

How long does the add method take, on average? Recall that n refers to the number of digits.