ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.

Slides:



Advertisements
Similar presentations
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;
Advertisements

Hip Hip Array! AP Computer Science. Remember Strings? Strings are an array of characters An array is a collection of variables all of the same type. Arrays.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
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.
PrimesFactory Lab Laugh if you get the pun. Don’t forget: You can copy- paste this slide into other presentations, and move or resize the poll. Poll:
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
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.
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.
Arrays And ArrayLists - S. Kelly-Bootle
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Stacks and Queues Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented Programming.
1 ArrayList  Array’s are limited because we need to know the size before we use them.  An ArrayList is an extension of an array that grows and shrinks.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 11 Arrays Continued
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.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
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.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
ArrayList By Neil Butcher. What is the difference between an ArrayList and an Array? An ArrayList is in many ways similar to an array, but has a few subtle.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Chapter 5 Array-Based Structures © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
Searching and Sorting 14ACEHRPT Copyright © 2011 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. Java Methods Object-Oriented.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
ITI Introduction to Computing II Lab-5 Dewan Tanvir Ahmed University of Ottawa.
Java Programming Persistent Data Types. Persistent Data Structure A persistent data structure is a data structure having an internal state that never.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
The ArrayList Data Structure The Most Important Things to Review.
Object Oriented Programming in Java Habib Rostami Lecture 7.
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();
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
 2016, Marcus Biel, ArrayList Marcus Biel, Software Craftsman
1 CS162: Introduction to Computer Science II Abstract Data Types.
(like an array on steroids)
COP 3503 FALL 2012 Shayan Javed Lecture 8
Implementing ArrayList Part 1
TCSS 143, Autumn 2004 Lecture Notes
Programming in Java Lecture 11: ArrayList
ArrayList Collections.
Grouped Data Arrays, and Array Lists.
ArrayLists 22-Feb-19.
slides created by Marty Stepp
Review of Previous Lesson
TCSS 143, Autumn 2004 Lecture Notes
Presentation transcript:

ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. TM

12½ - 2 Objectives: l Review interfaces l Learn about Comparable interface l Learn about the java.util.List interface and java.util.ArrayList class

12½ - 3 Interfaces l An interface specifies a list of one or more methods, giving only their signatures, but no code l A class implements an interface if it supplies code for all methods of that interface l If a class C implements an interface I, objects of C acquire a secondary data type, I l A class can implement several interfaces but it can extend only one class

12½ - 4 Interfaces: example public interface Sellable { double getPrice (); void setPrice (double price); } public class GroceryItem implements Sellable { private double myPrice; public double getPrice () { return myPrice; } public void setPrice (double price) { myPrice = price; } } Assumed public implements

12½ - 5 Interfaces (cont’d) l Why do we need them? –Situation one: public method calculateTax (Sellable obj, double rate) { return obj.getPrice() * rate; }... GrorceryItem apple = new GroceryItem("Apple", 0.30); double tax = calculateTax(apple, 0.05);... More generic type of parameter  more reusable code (works for any “Sellable” object)

12½ - 6 Interfaces (cont’d) –Situation two: private Sellable[ ] items = new Sellable[3]; items[0] = new GroceryItem(...); items[1] = new Pizza(...); items[2] = new JewelryItem(...); Different types of objects are mixed together in the same array or list

12½ - 7 Comparable Interface public interface Comparable { /** * Returns a positive integer if this is * "greater than" other, a negative integer if * this is "less than" other, and 0 if this is * "equal" to other */ int compareTo(Object other); } Kind of like this “minus” other

12½ - 8 Comparable (cont’d) «interface» java.lang.Comparable java.lang.Stringjava.lang.Integerjava.lang.Double compareTo is based on lexicographical order compareTo is based on numerical values

12½ - 9 Comparable example public class UsedCar implements Sellable, Comparable { private double myPrice; public int compareTo(Object other) { double diff = getPrice() - ((UsedCar) other).getPrice(); return (int)(100 * diff); // diff in cents } Forgetting a cast or parentheses results in a syntax error

12½ - 10 java.util.List Interface l The List library interface describes a list of objects in abstract terms l In a list, objects are arranged in sequence obj 0, obj 1,..., obj n - 1 l In Java, a list holds references to objects l A list can contain duplicate objects (both obj1.equals(obj2) and obj1 == obj2)

12½ - 11 List Methods (a Subset) int size(); boolean isEmpty (); boolean add (Object obj); void add (int i, Object obj); Object set(int i, Object obj); Object get(int i); Object remove(int i); boolean contains(Object obj); int indexOf(Object obj); returns true inserts obj as the i-th value; i must be from 0 to size() i must be from 0 to size() - 1 use equals to compare objects

12½ - 12 java.util.ArrayList l Implements List using an array l Keeps track of the list capacity (the length of the allocated array) and list size (the number of elements currently in the list) "Cat""Hat""Bat" capacity size

12½ - 13 ArrayList (cont’d) l Automatically increases (doubles) the capacity when the list runs out of space; allocates a bigger array and copies all the values into it l get(i) and set(i, obj) are efficient because an array provides random access to its elements l Throws IndexOutOfBoundsException when i < 0 or i  size()

12½ - 14 ArrayList (cont’d) l ArrayList holds objects (of any type) l If you need to put ints or doubles into a list, use a standard Java array or convert them into Integer or Double objects l You have to remember what types of objects your put into the list and may need to cast a retrieved object back into its type

12½ - 15 ArrayList (cont’d) l From Java API Docs:

12½ - 16 ArrayList list = new ArrayList (); list.add (new Integer(1)); list.add (new Integer(2)); list.add (new Integer(3)); int sum = 0; for (int i = 0; i < list.size(); i++) sum += ((Integer) list.get(i)). intValue(); ArrayList (cont’d) l Example 1 Need a cast to Integer in order to call intValue

12½ - 17 ArrayList words = new ArrayList (4); words.add ("One"); words.add ("Fish"); words.add ("Two"); words.add ("Fish"); int i = 0; while (i < words.size() ) { if ( ”Fish".equals (words.get(i)) ) words.remove(i); else i++; } ArrayList (cont’d) l Example 2 Shifts all the values after the i-th to the left and decrements the size

12½ - 18 Lab: Index Maker

12½ - 19 Index Maker (cont’d) IndexMaker IndexEntry DocumentIndex > java.util.List java.util.ArrayList implementsextends has

12½ - 20 Review: l How is an interface different from a class? l Can a class implement several interfaces? l Can an interface have more than one method? l If C is a class, when is the following statement valid? Comparable x = new C(); l What are the methods of Comparable?

12½ - 21 Review (cont’d): l Name the List methods that can add a value to the list. l Name the List methods that can tell you whether a given value is in the list. l In an ArrayList, should the indices be less than the size or less than the capacity? l What happens when the size of a List equals the capacity and you try to add a value?