3. Array-Lists.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

ArrayLists The lazy mans array. Whats the matter here? int[] list = new int[10]; list[0] = 5; list[2] = hey; list[3] = 15; list[4] = 23;
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
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.
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 05 / 03 / 2010 Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Arrays And ArrayLists - S. Kelly-Bootle
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
ArrayList, Multidimensional Arrays
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.
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
Copyright 2008 by Pearson Education Building Java Programs ArrayList Reading: 10.1.
CS 106 Introduction to Computer Science I 04 / 25 / 2008 Instructor: Michael Eckmann.
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.
(c) University of Washington15-1 CSC 143 Java List Implementation via Arrays Reading: 13.
(c) University of Washington16-1 CSC 143 Java Lists via Links Reading: Ch. 23.
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.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
An Array-Based Implementation of the ADT List
EKT472: Object Oriented Programming
CMSC 202 ArrayList Aug 9, 2007.
Using the Java Collection Libraries COMP 103 # T2
Generics, Exceptions and Undo Command
4. Linked Lists.
(like an array on steroids)
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Announcements & Review
Chapter 17 Object-Oriented Data Structures
Preconditions precondition: Something your method assumes is true at the start of its execution. Often documented as a comment on the method's header:
Introduction to Linked Lists
Welcome to CSE 143!.
Building Java Programs
TCSS 143, Autumn 2004 Lecture Notes
Lecture 2: Implementing ArrayIntList reading:
ArrayLists.
Programming in Java Lecture 11: ArrayList
ArrayLists.
(Java Collections Framework) AbstractSequentialList
CS Week 9 Jim Williams, PhD.
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.
CS 200 Objects and ArrayList
Arrays versus ArrayList
Winter 2018 CISC101 12/2/2018 CISC101 Reminders
CMSC 202 ArrayList Aug 9, 2007.
EE 422C Sets.
Welcome to CSE 143!.
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
Grouped Data Arrays, and Array Lists.
ArrayLists 22-Feb-19.
Review of Previous Lesson
List Implementation via Arrays
CSE 143 Lecture 4 Implementing ArrayIntList; Binary Search
ArrayLists.
slides created by Marty Stepp
ArrayLists 27-Apr-19.
CSE 143 Lecture 2 ArrayIntList, binary search
Review: libraries and packages
slides adapted from Marty Stepp
TCSS 143, Autumn 2004 Lecture Notes
CSE 143 Lecture 21 Advanced List Implementation
Arrays and ArrayLists.
slides created by Marty Stepp
Why not just use Arrays? Java ArrayLists.
slides created by Marty Stepp
Presentation transcript:

3. Array-Lists

Our First Data Structure! A wrapper around normal arrays. array problems: fixed-size, homogeneity ArrayLists fix the former (and could fix the latter) Java has one already… As do most languages …but I’m going to have you (partially) reinvent the wheel in lab3 Most data structures have the same operations add, remove, find, etc. Unless you understand the internals, you can’t choose the best one. That said, you’ll almost never do this in the real world

Java ArrayLists ArrayList a = new ArrayList(); // a heterogeneous ArrayList a.add("Bob"); a.add(15); // See the int vs. Integer slide… a.add(3.14f); // These are homogeneous ArrayLists ArrayList<String> b = new ArrayList<String>(); // This one ONLY holds Strings b.add("Bob"); //b.add(15); // Error ArrayList<Integer> c = new ArrayList<Integer>();// Only holds Integers //c.add("Bob"); c.add(15);

Major ArrayList operations void add(value new_val) adds the new value to the end of the list. Looks like it does this for free, but there is a cost… int getSize() void clear() int indexOf(value) finds the index of the first occurrence of a value (-1 if not found) boolean contains(value) similar to indexOf, but just returns true if found. Equivalent to “foo.indexOf(blah) != -1” value get(int index) Returns the value at the given position void set(int index, value new_val) Sets the value at the given index to the new value. void remove(int index) Removes the value at the given index. ArrayList subList(int start_index, int end_index) Returns a copy of the sub-list start_index is inclusive, end_index is exclusive Iterator iterator(): we’ll discuss this shortly.

iterators aka Java’s pimply wart. A way to “visit” each value in a data container in a consistent way. Example: This is a type-ignorant iterator. You often can do this to make it a type-aware iterator. Iterator I = a_container.iterator(); while (I.hasNext()) { my_value v = (my_value)I.next(); // do something with v. } Iterator<my_value> I = a_container.iterator(); … my_value v = I.next();

iterators, cont. hasNext next tells you (true / false) if there is more data waiting can be called any number of times. next advances the iteration and returns the next waiting value. can only be called once. is (usually) considered an error if you don’t call hasNext before calling next.

Basic Idea for our ArRAYLIST We make a class that internally has a normal array. We make it look as if that array can grow. When in reality, we have to re-allocate it and copy over The “growing” happens automatically We’re going to use a fixed increase-size We want to allow the user to do heterogeneous or homogeneous elements the major methods of Java’s ArrayList But first a few odds-and-ends…

Java primitives vs. Primitive-classes Java has two ways of representing primitives: int xp = 15; Integer xo = new Integer(15); // Or Integer xo = 15; // Same thing for float vs. Float, // boolean vs. Boolean, etc. Why? Normal primitives (e.g. int) more efficient no methods can’t do inheritance Class-based primivites (e.g. Integer) objects must be allocated with new (even if Java silently does it for you) has methods and can do inheritance. Derived as follows: Object Number Integer … Float Boolean String everything else in Java

Primitive-classes, cont. Why does this matter? Our ArrayList needs to hold any type of data It also needs to be capable of storing heterogeneous data This means internally, we’ll need an array of Objects When in actuality, it’s probably a derived class that gets stored in the internal array. This is allowed because of inheritance (like we saw in the last section)

Java Exceptions What are exceptions? An example A way to (normally) interrupt a program… …and indicate to the user what went wrong. An example Foo x; // forgot the new… x.bar(); // Null pointer exception We’re now on the “other side” We need to trigger an exception if the user incorrectly uses our ArrayList fast-fail = better (in my opinion)

Java Exceptions, cont. declaring a method that could throw one Java is adamant about this. If you might raise (throw) an exception, you must declare this in the method descriptor public void my_method(int val) throws IndexOutOfBoundsException { … if (…) throw new IndexOutOfBoundsException(“blah-blah”); }

Java Exceptions, cont. Exception types: https://www.tutorialspoint.com/java/java_builtin_exceptions.htm [not needed in this lab] handling exceptions A way to gracefully handle an exception try { // code that could raise a FooException } catch (FooException e) // e is the object created on the throw line.

enumerations A user-defined type that can only hold values from a finite list. public enum Colors {RED, BLUE, GREEN}; // elsewhere… Color c = Colors.BLUE; Color d = “Orange”; // Error Color e = 15; // Error

Generics Whew – that was a lot of odds-and-ends! Now we’re ready to start. First attempt Problems? Only holds ints would have to make a new class for other types (inheritance might help…a little) Can’t hold heterogeneous data. class IntArrayList { protected int[] mData; public void add(int i) { … }; // other stuff… } // in main… IntArrayList I = new IntArrayList(); I.add(15);

Generics, cont. Second attempt Better: can do heterogeneous lists class ArrayList { protected Object[] mData; public void add(Object i) { … }; // other stuff… } // in main… ArrayList I = new ArrayList(); I.add(15); I.add(“Bob”); Second attempt Better: can do heterogeneous lists Bad: can’t enforce homogeneous lists.

Generics, cont. A combination of Attemp2 and Java Generics let us solve the problem. Java Generics A way to make a generic class When the user creates an instance of that class, they can optionally specify an actual type A brand-new class is created behind the scenes with that type If not type is supplied, class Object is assumed

Generics, cont. class ArrayList<E> { protected Object[] mData; public void add(E i) { … }; // other stuff… } // in main… ArrayList I = new ArrayList(); // Same as ArrayList<Object> I = new ArrayList<Object>(); I.add(15); I.add(“Bob”); ArrayList<String> J = new ArrayList<String>(); J.add(“Bob”); J.add(15); // Error!

Sorted ArrayLists Java doesn’t have this A good example of extends inheritance SortedArrayList should do everything that ArrayList does… …but add (and find) elements in-order either Ascending or Descending (the user should tell us which when they create it) use an enumeration! Adding: Much slower than ArrayList add (our method) Search for the correct spot, move all remaining elements over (System.arraycopy), and insert Finding Much faster than ArrayList indexOf / contains Can use Binary Search

Binary Search [Discuss 1-100 guessing game] Ideal strategy: Look at middle element If: It’s equal to the element we were looking for, we’re done! It’s too small, look at the latter half It’s too big, look at the beginning half Need to maintain a left and right index initially 0 and n repeat as long as left <= right: calculate middle index (half-way between left and right) if too small, set left to middle+1 if too big, set right to middle-1

javadocs A standard way of documenting code [Example] Most IDE’s complete the ugly formatting if you type /**, then hit enter. Two types Method Class / enumeration Can be used to auto-generate documentation [Demo it] /** * Finds the first occurrence of the given value in our array. * @param value: The value to find. * @return: The index at which that value appears within mData (or -1 * if that value is not in the array) */ public int indexOf(E value) { }

Let’s get started! Options: [Develop the skeleton code together in-class, including test program] [Just give you the test program] Optionally start skeleton code next time.