Array Lists and Arrays Sections 13.1, 13.3 Common Errors 13.1, 13.2

Slides:



Advertisements
Similar presentations
The ArrayList Class and the enum Keyword
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.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Arrays And ArrayLists - S. Kelly-Bootle
11: Holding Your Objects Introduction to containers Container disadvantage: unknown type Iterators Container taxonomy Collection functionality List functionality.
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.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Goals for Today  implement a Deck of Cards  composition  Iterator interface  Iterable interface 1.
1 Dr. Seuss again: "Too Many Daves"  Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave?  Well, she did. And that.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
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.
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.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 20 Lists, Stacks, Queues, and Priority.
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.
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
The ArrayList Data Structure Standard Arrays at High Speed!
Java Collection Classes Com379PT
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
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.
The AP Java Subset Topics. A Topics Primitive Types int double boolean.
Coming up ArrayList ArrayList vs Array – Declaration – Insertion – Access – Removal Wrapper classes Iterator object.
1 CS162: Introduction to Computer Science II Abstract Data Types.
Exposure Java 2011 APCS Edition
EKT472: Object Oriented Programming
CMSC 202 ArrayList Aug 9, 2007.
Sixth Lecture ArrayList Abstract Class and Interface
Lecture 20: Wrapper Classes and More Loops
(like an array on steroids)
Lists Chapter 4.
ARRAYLIST AND VECTOR.
COP 3503 FALL 2012 Shayan Javed Lecture 8
Implementing ArrayList Part 1
Java collections library
Chapter-7 part3 Arrays Two-Dimensional Arrays The ArrayList Class.
Top Ten Words that Almost Rhyme with “Peas”
Java Software Structures: John Lewis & Joseph Chase
TCSS 143, Autumn 2004 Lecture Notes
"First things first, but not necessarily in that order " -Dr. Who
Programming in Java Lecture 11: ArrayList
Chapter 8 Slides from GaddisText
CMSC 202 ArrayList Aug 9, 2007.
CMSC 202 ArrayList Aug 9, 2007.
Collections Not in our text.
Grouped Data Arrays, and Array Lists.
Chapter 6 Array-Based Lists.
slides created by Ethan Apter
Java Array Lists 2/13/2017.
ArrayLists 22-Feb-19.
Review of Previous Lesson
Programming II (CS300) Chapter 02: Using Objects Java ArrayList Class
Creating and Modifying Text part 3
Review: libraries and packages
Object-Oriented Programming Part 3 Bank Account Embezzling
TCSS 143, Autumn 2004 Lecture Notes
TCSS 143, Autumn 2004 Lecture Notes
Java Coding 6 David Davenport Computer Eng. Dept.,
What can you put into an ArrayList?
Presentation transcript:

Array Lists and Arrays Sections 13.1, 13.3 Common Errors 13.1, 13.2 Chapter 13 Array Lists and Arrays Sections 13.1, 13.3 Common Errors 13.1, 13.2 Fran Trees Drew University

Dr. Seuss again: "Too Many Daves" Did I ever tell you that Mrs. McCave Had twenty-three sons, and she named them all Dave? Well, she did. And that wasn't a smart thing to do. You see, when she wants one, and calls out "Yoo-Hoo! Come into the house, Dave!" she doesn't get one. All twenty-three Daves of hers come on the run! Fran Trees Drew University

"Too Many Daves" This makes things quite difficult at the McCaves' As you can imagine, with so many Daves. And often she wishes that, when they were born, She had named one of them Bodkin Van Horn. And one of them Hoos-Foos. And one of them Snimm. And one of them Hot-Shot. And one Sunny Jim. Another one Putt-Putt. Another one Moon Face. Another one Marvin O'Gravel Balloon Face. And one of them Zanzibar Buck-Buck McFate... But she didn't do it. And now it's too late. http://www.mit.edu/people/dpolicar/writing/poetry/poems/tooManyDaves.html Fran Trees Drew University

This is not all that bad….. Come into the house, Dave!" she doesn't get one. All twenty-three Daves of hers come on the run! Fran Trees Drew University

ArrayList It is very common for applications to require us to store a large amount of data. Array Lists store large amounts of data in a single collection that can be referred to with a single variable. Fran Trees Drew University

ArrayList An ArrayList is a sequence of objects that grows and shrinks as needed. The ArrayList class is part of the java.util package of the Java standard class library. Fran Trees Drew University

ArrayList Each element in the sequence can be accessed separately. We can explicitly overwrite an object at a specified position in the sequence, thus changing its value. We can inspect the object at a specified location in the sequence. We can add an object into a specified position of the sequence. We can add an object to the end of the sequence. We can remove an object from a specified location in the sequence. Fran Trees Drew University

interface java.util.List boolean add(Object x) // appends x to the end of list; returns true int size() // returns the number of elements in this list Object get(int index) // returns the element at the specified position in this list. Object set(int index, Object x) // replaces the element at index with x // returns the element formerly at the specified position Iterator iterator() ListIterator listIterator() Fran Trees Drew University

class java.util.ArrayList implements java.util.List Methods in addition to the List methods: void add(int index, Object x) // inserts x at position index, sliding elements // at position index and higher to the right // (adds 1 to their indices) and adjusts size Object remove(int index) // removes element from position index, sliding // subsequent elements to the left (subtracts 1 from their //indices) and adjusts size // returns the element at the specified position in this list. Fran Trees Drew University

An example: import java.util.ArrayList; import java.util.Iterator; public class ArrayListTest { public static void main (String [] arg) System.out.println("\nArrayListTest \n"); ArrayList aList = new ArrayList(); aList.add("Dan"); aList.add("George"); aList.add("Mary"); System.out.println("aList contains:"); for(int x = 0; x < aList.size(); x++) System.out.println(aList.get(x)); } Fran Trees Drew University

Using an Iterator import java.util.ArrayList; import java.util.Iterator; public class ArrayListTest { public static void main (String [] arg) System.out.println("\nArrayListTest \n"); ArrayList aList = new ArrayList(); aList.add("Dan"); aList.add("George"); aList.add("Mary"); System.out.println("aList contains:"); Iterator it = aList.iterator(); while (it.hasNext()) System.out.println(it.next()); } Fran Trees Drew University

What happens? ArrayList students = new ArrayList(); students.add("Mary"); students.add("James"); students.add("Kevin"); students.add(1, "Tanya"); String temp = (String)students.get(3); System.out.println(temp); students.remove(2); students.set(1, "John"); System.out.println(students.size()); Fran Trees Drew University

What happens? Mary James Kevin Mary Tanya James Kevin Mary Tanya Kevin ArrayList students = new ArrayList(); students.add("Mary"); students.add("James"); students.add("Kevin"); students.add(1, "Tanya"); String temp = (String)students.get(3); System.out.println(temp); students.remove(2); students.set(1, "John"); Mary James Kevin Mary Tanya James Kevin temp Mary Tanya Kevin Mary John Kevin Fran Trees Drew University

An ArrayList is a sequence of objects. Array lists can hold any kind of object. ArrayList athletes = new ArrayList(); ArrayList csci6 = new ArrayList(); ArrayList accounts = new ArrayList(); The ArrayList method add adds an Object. The ArrayList method get returns an Object. Fran Trees Drew University

An ArrayList is a sequence of objects. Array lists can hold any kind of object. ArrayList athletes = new ArrayList(); ArrayList csci6 = new ArrayList(); ArrayList accounts = new ArrayList(); The ArrayList method add adds an Object. The ArrayList method get returns an Object. Fran Trees Drew University

An ArrayList is a sequence of objects. boolean add(Object x) Can I do this??? ArrayList aList = new ArrayList(); aList.add(new Athlete("Dan","Smith","SkiJumping")); aList.add(new Athlete("George","Harris","Swimming")); aList.add(new Athlete("Mary","Jones","Tennis")); Fran Trees Drew University

An ArrayList is a sequence of objects. boolean add(Object x) Can I do this??? ArrayList aList = new ArrayList(); aList.add(new Athlete("Dan","Smith","SkiJumping")); aList.add(new Athlete("George","Harris","Swimming")); aList.add(new Athlete("Mary","Jones","Tennis")); Yes…an Athlete IS-A Object. Fran Trees Drew University

An ArrayList is a sequence of objects. Object get(int x) Can I do this??? ArrayList aList = new ArrayList(); aList.add(new Athlete("Dan","Smith","SkiJumping")); aList.add(new Athlete("George","Harris","Swimming")); aList.add(new Athlete("Mary","Jones","Tennis")); for(int x = 0; x < aList.size(); x++) { System.out.println(aList.get(x).getName()); } Fran Trees Drew University

An ArrayList is a sequence of objects. Object get(int x) Can I do this??? ArrayList aList = new ArrayList(); aList.add(new Athlete("Dan","Smith","SkiJumping")); aList.add(new Athlete("George","Harris","Swimming")); aList.add(new Athlete("Mary","Jones","Tennis")); for(int x = 0; x < aList.size(); x++) { System.out.println(aList.get(x).getName()); } NO… getName() is NOT a method of Object. Fran Trees Drew University

An ArrayList is a sequence of objects. Object get(int x) Fix it. ArrayList aList = new ArrayList(); aList.add(new Athlete("Dan","Smith","SkiJumping")); aList.add(new Athlete("George","Harris","Swimming")); aList.add(new Athlete("Mary","Jones","Tennis")); for(int x = 0; x < aList.size(); x++) { System.out.println(aList.get(x).getName()); } Fran Trees Drew University

An ArrayList is a sequence of objects. Object get(int x) Fix it. ArrayList aList = new ArrayList(); aList.add(new Athlete("Dan","Smith","SkiJumping")); aList.add(new Athlete("George","Harris","Swimming")); aList.add(new Athlete("Mary","Jones","Tennis")); for(int x = 0; x < aList.size(); x++) { System.out.println (((Athlete)aList.get(x)).getName() + "\n"); } Fran Trees Drew University

An ArrayList is a sequence of objects. Object get(int x) I prefer….. ArrayList aList = new ArrayList(); aList.add(new Athlete("Dan","Smith","SkiJumping")); aList.add(new Athlete("George","Harris","Swimming")); aList.add(new Athlete("Mary","Jones","Tennis")); for(int x = 0; x < aList.size(); x++) { Athlete fit = (Athlete)aList.get(x); System.out.println(fit.getName() + "\n"); } Fran Trees Drew University

Some notes about ArrayList An ArrayList is a sequence of objects. Each object in an array list has an integer position (index). get returns an Object. You need to cast the object to the element class. Position numbers in an array list are 0..size() – 1. Adding or removing elements from an array list is more work than it seems! Fran Trees Drew University

A bit more about…. Casting Fran Trees Drew University

private int catNumber; Cat (int i) catNumber = i; } public class Cat { private int catNumber; Cat (int i) catNumber = i; } public void print() System.out.println("Cat #" + catNumber); Fran Trees Drew University

private int dogNumber; Dog(int i) dogNumber = i; } public void print() public class Dog { private int dogNumber; Dog(int i) dogNumber = i; } public void print() System.out.println("Dog #" + dogNumber); Fran Trees Drew University

import java.util.ArrayList; public class CatsAndDogs { public static void main(String[] args) ArrayList cats = new ArrayList(); for (int i = 0; i < 7; i++) cats.add(new Cat(i)); } cats.add(new Dog(7)); //Can I do this? for(int i = 0; i < cats.size(); i++) System.out.println(cats.get(i)); // Does this print anything? // If so, what? Fran Trees Drew University

What happened? What is this? ArrayList cats = new ArrayList(); for (int i = 0; i < 7; i++) { cats.add(new Cat(i)); } cats.add(new Dog(7)); for(int i = 0; i < cats.size(); i++){ System.out.println(cats.get(i)); Cat@ba34f2 Cat@ea2dfe Cat@7182c1 Cat@3f5d07 Cat@f4a24a Cat@cac268 Cat@a16869 Dog@cde100 What happened? What is this? Fran Trees Drew University

ArrayList cats = new ArrayList(); for (int i = 0; i < 7; i++) { cats.add(new Cat(i)); } cats.add(new Dog(7)); for(int i = 0; i < cats.size(); i++) ((Cat) cats.get(i)).print(); // Does this print anything? // If so, what? Fran Trees Drew University

Prints….. WHY? Cat #0 Cat #1 Cat #2 Cat #3 Cat #4 Cat #5 Cat #6 Exception in thread "main" java.lang.ClassCastException: Dog at CatsAndDogs.main(CatsAndDogs.java:15) Press any key to continue... WHY? Fran Trees Drew University

Hmmmm…. Object obj = new Cat(3); obj.print(); //Can I do this? Fran Trees Drew University

Hmmmm…. Object obj = new Cat(3); *obj.print(); // Nope! // The compiler can determine only that the object is an Object and could possible refer to a Dog object or a Rectangle object, so it doesn't allow the reference *. Fran Trees Drew University

But…. Object obj = new Cat(3); ((Cat)obj).print(); // But I can do THIS. // What about the parenthesis? Fran Trees Drew University

And…. Cat aCat = new Cat(3); Object obj = aCat; //Can I do THIS? Fran Trees Drew University

And…. Cat aCat = new Cat(3); Object obj = aCat; //Yep! I can assign a reference variable to the class that it extends. aCat can be assigned to the class that it extends(Object). This is Java's one-way assignment compatibility. aCat IS A Object. Fran Trees Drew University

What about…. Cat aCat = new Cat(3); Object obj = aCat; obj.print(); Fran Trees Drew University

What about…. Cat aCat = new Cat(3); Object obj = aCat; obj.print(); //nope ! Fran Trees Drew University

Must…. Cat aCat = new Cat(3); Object obj = aCat; ((Cat)obj).print(); //yep ! Fran Trees Drew University

Let's try more… Fran Trees Drew University

Can I do this? Object anObject = null; String stringA = "hello"; anObject = stringA; Fran Trees Drew University

Object anObject = null; String stringA = "hello"; anObject = stringA; //OK Fran Trees Drew University

Can I do this? Object anObject = null; String stringA = "hello"; stringA = anObject; Fran Trees Drew University

Object anObject = null; String stringA = "hello"; stringA = anObject; needs cast Fran Trees Drew University

Can I do this? Object anObject = null; String stringA = "hello"; Comparable c = new Comparable(); Fran Trees Drew University

Object anObject = null; String stringA = "hello"; Comparable c = new Comparable(); No, Comparable is an interface. Fran Trees Drew University

Can I do this? Object anObject = null; String stringA = "hello"; Comparable c = new String(); Fran Trees Drew University

Object anObject = null; String stringA = "hello"; Comparable c = new String(); Yes, String implements Comparable Fran Trees Drew University

A bit more about toString() Fran Trees Drew University

What happens? public class StringTest { public static void main(String[] args) ArrayList stringList = new ArrayList(); stringList.add("Fran"); stringList.add("Marie"); stringList.add("Joe"); System.out.println(stringList); } Fran Trees Drew University

WHY???? public class StringTest { public static void main(String[] args) ArrayList stringList = new ArrayList(); stringList.add("Fran"); stringList.add("Marie"); stringList.add("Joe"); System.out.println(stringList); } [Fran, Marie, Joe] Let's look at the API! Fran Trees Drew University

What happens? public class Strings { public static void main(String[] args){ ArrayList stringList = new ArrayList(); stringList.add("Fran"); stringList.add("Marie"); stringList.add("Joe"); String aStringInList = stringList.get(0); // is this OK? } Fran Trees Drew University

no…but public class Strings { public static void main(String[] args) ArrayList stringList = new ArrayList(); stringList.add("Fran"); stringList.add("Marie"); stringList.add("Joe"); String aStringInList = (String)stringList.get(0); //NOW this is OK. } //What about parentheses? } Fran Trees Drew University

What happens? public class Strings { public static void main(String[] args){ ArrayList stringList = new ArrayList(); stringList.add("Fran"); stringList.add("Marie"); stringList.add("Joe"); System.out.println(stringList.get(0)); //Can I do this?????? } Fran Trees Drew University

What happens? public class Strings { public static void main(String[] args) ArrayList stringList = new ArrayList(); stringList.add("Fran"); stringList.add("Marie"); stringList.add("Joe"); System.out.println(stringList.get(0)); //YEP….what is printed? } Fran Trees Drew University

What happens? public class Strings { public static void main(String[] args) ArrayList stringList = new ArrayList(); stringList.add("Fran"); stringList.add("Marie"); stringList.add("Joe"); System.out.println(stringList.get(0)); //Fran } Fran Trees Drew University

AGAIN… An ArrayList is a sequence of objects. Array lists can hold any kind of object. The ArrayList method add adds an Object. The ArrayList method get returns an Object. What is we want our ArrayList to hold ints or doubles? Fran Trees Drew University

Wrapper Classes Another look at the API Integer(int value) class java.lang.Integer implements java.lang.Comparable Integer(int value) int intValue() boolean equals(Object other) String toString() int compareTo(Object other) Another look at the API Fran Trees Drew University

Wrapper Classes Another look at the API Double(double value) class java.lang.Double implements java.lang.Comparable Double(double value) double doubleValue() boolean equals(Object other) String toString() int compareTo(Object other) Another look at the API Fran Trees Drew University

Filling the ArrayList for (int k = 1; k <= 20; k++) { nbrs.add(new Integer(k)); } Fran Trees Drew University

Printing the ArrayList for (int k = 0; k < nbrs.size(); k++) { System.out.print("\t" + nbrs.get(k)); } System.out.println(); Fran Trees Drew University

Printing the sum of the integer values in the ArrayList int sum = 0; Integer temp; for (int k = 0; k < nbrs.size(); k++) { temp = (Integer)nbrs.get(k); sum += temp.intValue(); } System.out.println("sum equals: " + sum); Fran Trees Drew University

ArrayList Applications Finding values, counting, max and min, average, median, mode….. But first….LOTTERY Fran Trees Drew University

CRC cards This program will simulate the TV Lottery drawing for the Pick-6 New Jersey Lottery game. In this game, balls are placed in a container that keeps them popping around in some random movements. The "LotteryPicker" picks a ball from the container (6 times). The chosen balls are displayed. Fran Trees Drew University

Candidate classes Ball Game Picker Hopper Fran Trees Drew University

A lottery game Judy Hromcik 3 classes Ball Class the numbered item Picker Class the person that gets the ball from the Hopper Hopper Class the jug-like container that holds the balls Fran Trees Drew University

Ball Class public class Ball { public Ball() //default constructor-sets value to 0 public Ball(int val) //sets value to val public int value() //returns value on ball public String toString() //displays ball private int myValue; } Fran Trees Drew University

Hopper Class public class Hopper { public Hopper() //adds default # balls to ArrayList myBalls public Hopper(int numBalls) //adds numBalls # balls to ArrayList my Balls public int size() //returns # balls in Hopper public Ball getBall(int j) removes the jth ball from Hopper private ArrayList myBalls; private static int DEFAULT_NUM_BALLS = <some default int goes here>; } Fran Trees Drew University

Picker Class public class Picker { public Picker() //gets a Hopper (default) public Picker(int numBalls) //gets a Hopper with numBalls balls public Ball chooseBall() //chooses a random ball from Hopper private static Random generator = new Random(); Hopper myHopper; } Fran Trees Drew University

Two implementations: Text version Graphics version Both use SAME three classes Fran Trees Drew University