Presentation is loading. Please wait.

Presentation is loading. Please wait.

3. Array-Lists.

Similar presentations


Presentation on theme: "3. Array-Lists."— Presentation transcript:

1 3. Array-Lists

2 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

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

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

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

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

7 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…

8 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

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

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

11 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”); }

12 Java Exceptions, cont. Exception types: [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.

13 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

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

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.

16 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

17 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!

18 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

19 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

20 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. value: The value to find. The index at which that value appears within mData (or -1 * if that value is not in the array) */ public int indexOf(E value) { }

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


Download ppt "3. Array-Lists."

Similar presentations


Ads by Google