Lists Ellen Walker CPSC 201 Data Structures Hiram College.

Slides:



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

Why not just use Arrays? Java ArrayLists.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
ITEC200 Week04 Lists and the Collection Interface.
M180: Data Structures & Algorithms in Java
ArrayLists David Kauchak cs201 Spring Extendable array Arrays store data in sequential locations in memory Elements are accessed via their index.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Stacks. 2 Outline and Reading The Stack ADT (§4.2.1) Applications of Stacks (§4.2.3) Array-based implementation (§4.2.2) Growable array-based stack.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Lists and Iterators (Chapter 6) COMP53 Oct 22, 2007.
List Implementations That Use Arrays Chapter 5. 2 Chapter Contents Using a Fixed-Size Array to Implement the ADT List An Analogy The Java Implementation.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5) Java.util.Stack class Java.util.Vector.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
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.
Alice in Action with Java
Stacks. 2 Outline and Reading The Stack ADT (§2.1.1) Applications of Stacks (§2.1.1) Array-based implementation (§2.1.1) Growable array-based stack (§1.5)
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Odds and Ends Strings (from Chapter 9) StringTokenizer.
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 19 Java Data Structures
Arrays And ArrayLists - S. Kelly-Bootle
Topic 3 The Stack ADT.
Implementing Stacks Ellen Walker CPSC 201 Data Structures Hiram College.
CHAPTER 05 Compiled by: Dr. Mohammad Omar Alhawarat Stacks & Queues.
Chapter 3 Introduction to Collections – Stacks Modified
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Hash Functions and the HashMap Class A Brief Overview On Green Marble John W. Benning.
ArrayList, Multidimensional Arrays
Chapter 11 Arrays Continued
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Stacks. A stack is a data structure that holds a sequence of elements and stores and retrieves items in a last-in first- out manner (LIFO). This means.
GENERICS. Generics  Classes and methods can have a type parameter (actually, more than one).  The type parameter can be any reference (class) type.
Chapter 18 Java Collections Framework
Data structures Abstract data types Java classes for Data structures and ADTs.
April 24, 2017 Chapter 4 Data Abstraction The Walls
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.
Lists and the Collection Interface Chapter 4. 2 The List Interface and ArrayList Class So far, all we have is an array for storing a collection of elements.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
Dynamic Data Structures and Generics Chapter 10. Outline Vectors Linked Data Structures Introduction to Generics.
Dynamic Array. An Array-Based Implementation - Summary Good things:  Fast, random access of elements  Very memory efficient, very little memory is required.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Array Lists1 © 2010 Goodrich, Tamassia. Array Lists2 The Array List ADT  The Array List ADT extends the notion of array by storing a sequence of arbitrary.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Chapter Objectives  The List interface  Implement lists based on arrays  Learn about List applications CS340 1.
List Interface and Linked List Mrs. Furman March 25, 2010.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
M180: Data Structures & Algorithms in Java Stacks Arab Open University 1.
The ArrayList Data Structure Standard Arrays at High Speed!
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
An Array-Based Implementation of the ADT List
Lists and Iterators 5/3/2018 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia,
Sixth Lecture ArrayList Abstract Class and Interface
COP 3503 FALL 2012 Shayan Javed Lecture 8
Top Ten Words that Almost Rhyme with “Peas”
Stacks.
" A list is only as strong as its weakest link. " - Donald Knuth
Arrays versus ArrayList
Queues 12/30/2018 9:24 PM Queues 12/30/2018 9:24 PM Queues.
ArrayLists 22-Feb-19.
slides created by Alyssa Harding
Presentation transcript:

Lists Ellen Walker CPSC 201 Data Structures Hiram College

What is a List (abstract)? Sequence of objects Objects are in order –There is a first object –There is a last object –Each object (except last) has a successor –Each object (except first) has a predecessor List can be changed –Objects can be added (list grows) –Objects can be removed (list shrinks)

Some Operations on a List Construct a new list Add an element –Indicate where (beginning, end, middle?) Remove an element –Indicate which one (how?) Find an element in the list Check whether the list is empty or not (etc)

List vs. Array List is more general than array –List is abstract, array is an implementation List is more flexible than array –List can grow or shrink; array is fixed size List contains Objects, array can contain base types –Use wrappers (e.g. Integer) with boxing/unboxing in a List

List Class Hierarchy

Choosing an Implementation Any implementation will implement all methods of the interface (by definition) But –Some implementations might be more efficient at some operations Example: –Removing element from middle of list ArrayList: shift all elements to fill the “hole” - O(N) LinkedList: adjust successor of element before the removed one O(1)

ArrayList Implementation The list is stored in an array, which is a private member of the ArrayList (you cannot access it) This array has a capacity When the number of elements in the list exceeds the capacity, the internal array is replaced by a bigger one

Constructing an ArrayList ArrayList() –Constructs initially empty list, capacity of 10 ArrayList(int capacity) –Constructs initially empty list with given capacity Example: Both lists are empty (size of 0), but A has capacity of 10, and B has capacity of 5 –ArrayList A = new ArrayList(); –ArrayList B = newArrayList(5);

Specifying Element Types Generics - specify element type in //Construct an ArrayList that holds strings List myList = new ArrayList (); //An ArrayList of Circles List myList = new ArrayList (); Without type specification, Object is assumed –Backwards compatible with Java before 5.0

Why Generic Collections? Old-style needs casting, compiler cannot check –List myList = new ArrayList(); –myList.add(new Integer(5)); //any Object is OK –System.out.println((String) myList.get(0)); //runtime error: cannot cast Integer to String Generic - Compiler error –List myList = new ArrayList (); –myList.add(new Integer(5)); //compiler error - type mismatch

Why Generic Collections? Old-style: Objects must be explicitly wrapped List List1 = new ArrayList(); List1.add(5); //error Generic: Autoboxing takes care of it List List1 = new ArrayList (); List1.add(5); //new Integer(5) created and inserted

Adding Elements For an ArrayList –ArrayList rainbow = new ArrayList (5); add (E obj) - adds obj to the end of the list –rainbow.add(“green”); –rainbow.add(“violet”); add (int index, E obj) - adds obj at position index of the list –rainbow.add(0, “red”) –rainbow.add(2, “blue”);

Accessing and Changing Elements Use get() and set() instead of [ ] for ArrayLists –More general (works for other list types) Get method –aColor = rainbow.get(1); –for(int c=0;c<rainbow.size();c++) System.out.println(rainbow.get(c)); Set method –rainbow.set(1, “Crimson”);

Summary: Java ArrayList

More examples What add statements are needed to complete the rainbow? (red, orange, yellow, green, blue, indigo, violet) What statement will change “indigo” to “purple”? What will rainbow.indexOf(“orange”) return? What will rainbow.indexOf(“elephant”) return?

Application vs. Implementation We now know enough to apply the ArrayList class, but… To really understand an ADT, we should learn about its implementation We will implement classes similar to each of the collection classes we study –ArrayList vs. KWArrayList –LinkedList vs. KWLinkedList …

Implementation of an ArrayList Class KWArrayList: simple implementation of a ArrayList class –Physical size of array indicated by data field capacity –Number of data items indicated by the data field size

Implementation of an ArrayList Class (continued)

Overview of KWArrayList Data Members –Private static final int INITIAL_CAPACITY = 10; –Private E[ ] theData; //array for data –Private int size = 0; //current size –Private int capacity = 0; //current capacity Default constructor –Sets capacity and creates an array for theData

Overview of KWArrayList (cont) Public boolean add (E anEntry) –Check if the array is full; if so then reallocate –theData[size] = anEntry; –Increment size Public boolean add (int index, E anEntry) –Check if the array is full; if so then reallocate –Shift elements beyond index to make room –theData[index] = anEntry –Increment size

Overview of KWArrayList (cont) Public E remove(int index) –Shift all items after index left by one space –Decrement size –Return the element that was removed Private void reallocate () –Double the capacity –Create a new array of the appropriate size –Copy all the data into the new array

Cost of Reallocation Every time we reallocate, we copy capacity entries into the new array (of size 2*capacity) Cost is proportional to the capacity (C*capacity) Since we reallocate only after adding capacity items we have: –Capacity -1 additions (0 extra cost) –1 addition (C*capacity extra cost) Averaging it out, the extra cost is constant per addition

Performance of KWArrayList Set and get methods execute in constant time Inserting or removing elements is linear time –What is worst case of removing an element? –What is worst case of inserting an element? (Hint: consider capacity of the list) IndexOf is linear time