Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 10: ArrayList.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

Generics, Lists, Interfaces
Computer Science 209 Software Development Equality and Comparisons.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Slides prepared by Rose Williams, Binghamton University Chapter 14 Generics and the ArrayList Class.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Building Java Programs
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
ARRAYS AND ARRAYLISTS Chapter 7. Array  Sequence of values of the same type  Primitive types  Objects  Create an Array  double[] values = new double[10]
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Programming With Java ICS201 University Of Ha’il1 Chapter 14 Generics and The ArrayList Class.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
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.. Hazen High School. Vocabulary to Know ArrayList Generic Class ArrayList Operations ArrayList Methods ArrayList Searching For-Each Wrapper.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
Chapter 11 Arrays Continued
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Copyright 2008 by Pearson Education Building Java Programs Chapter 10 Lecture 10-1: ArrayList reading: 10.1.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Copyright 2008 by Pearson Education Building Java Programs ArrayList Reading: 10.1.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
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.
CSE 143 Lecture 2 ArrayList reading: 10.1 slides created by Marty Stepp
© 2004 Pearson Addison-Wesley. All rights reserved October 15, 2007 Searching ComS 207: Programming I (in Java) Iowa State University, FALL 2007 Instructor:
CS-2851 Dr. Mark L. Hornick 1 Generic Java Classes Implementing your own generic classes.
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 7: Arrays.
Copyright 2010 by Pearson Education Building Java Programs Chapter 10, 11 Lecture 22: 143 Preview optional reading: 10.1,
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 4 Exceptions and ArrayList slides created by Marty Stepp
CSE 1201 Object Oriented Programming ArrayList 1.
ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
CSE 143 Lecture 3 Implementing ArrayIntList reading: slides created by Marty Stepp and Hélène Martin
Building Java Programs Chapter 10 ArrayList Copyright (c) Pearson All rights reserved.
CMSC 202 ArrayList Aug 9, 2007.
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Chapter 20 Generic Classes and Methods
Primitive Types Vs. Reference Types, Strings, Enumerations
Building Java Programs
TCSS 143, Autumn 2004 Lecture Notes
Lecture 2: Implementing ArrayIntList reading:
Building Java Programs
Building Java Programs
ArrayLists.
CMSC 202 ArrayList Aug 9, 2007.
Lecture 2: Implementing ArrayIntList reading:
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
slides created by Ethan Apter
CSE 143 Lecture 3 Implementing ArrayIntList reading:
CSE 143 Lecture 4 Implementing ArrayIntList; Binary Search
Dr. Sampath Jayarathna Cal Poly Pomona
CSE 143 Lecture 2 ArrayIntList, binary search
CSE 143 Lecture 4 Implementing ArrayIntList reading:
Arrays.
Implementing ArrayIntList
Presentation transcript:

Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 10: ArrayList

Copyright 2006 by Pearson Education 2 Chapter outline ArrayList basic operations searching for elements wrapper classes Comparable interface natural ordering and compareTo implementing Comparable

Copyright 2006 by Pearson Education 3ArrayList reading: 10.1

Copyright 2006 by Pearson Education 4 Lists list: an ordered sequence of elements, each accessible by a 0-based index one of the most basic collections of data

Copyright 2006 by Pearson Education 5 The ArrayList class Class ArrayList implements the notion of a list using a partially-filled array when you want to use ArrayList, remember to import java.util.*;

Copyright 2006 by Pearson Education 6 ArrayList features think of it as an auto-resizing array that can hold any type of object, with many convenient methods maintains most of the benefits of arrays, such as fast random access frees us from some tedious operations on arrays, such as sliding elements and resizing can call toString on an ArrayList to print its elements [1, 2.65, Marty Stepp, Hello]

Copyright 2006 by Pearson Education 7 Generic classes generic class: A type in Java that is written to accept another type as part of itself. Generic ("parameterized") classes were added to Java to improve the type safety of Java's collections. A parameterized type has one or more other types' names written between. ArrayList is a generic class. The is a placeholder in which you write the type of elements you want to store in the ArrayList. Example: ArrayList words = new ArrayList (); Now the methods of words will manipulate and return String s.

Copyright 2006 by Pearson Education 8 ArrayList vs. array array String[] names = new String[5]; names[0] = "Jennifer"; String name = names[0]; ArrayList ArrayList namesList = new ArrayList (); namesList.add("Jennifer"); String name = namesList.get(0);

Copyright 2006 by Pearson Education 9 Adding elements Elements are added dynamically to the list: ArrayList list = new ArrayList (); System.out.println("list = " + list); list.add("Tool"); System.out.println("list = " + list); list.add("Phish"); System.out.println("list = " + list); list.add("Pink Floyd"); System.out.println("list = " + list); Output: list = [] list = [Tool] list = [Tool, Phish] list = [Tool, Phish, Pink Floyd]

Copyright 2006 by Pearson Education 10 Removing elements Elements can also be removed by index: System.out.println("before remove list = " + list); list.remove(0); list.remove(1); System.out.println("after remove list = " + list); Output: before remove list = [Tool, U2, Phish, Pink Floyd] after remove list = [U2, Pink Floyd] Notice that as each element is removed, the others shift downward in position to fill the hole. Therefore, the second remove gets rid of Phish, not U2. index0123 valueToolU2PhishPink Floyd index012 valueU2PhishPink Floyd index01 valueU2Pink Floyd

Copyright 2006 by Pearson Education 11 Searching for elements You can search the list for particular elements: if (list.contains("Phish")) { int index = list.indexOf("Phish"); System.out.println(index + " " + list.get(index)); } if (list.contains("Madonna")) { System.out.println("Madonna is in the list"); } else { System.out.println("Madonna is not found."); } Output: 2 Phish Madonna is not found. contains tells you whether an element is in the list or not, and indexOf tells you at which index you can find it.

Copyright 2006 by Pearson Education 12 ArrayList methods Method nameDescription add( value ) adds the given value to the end of the list add( index, value ) inserts the given value before the given index clear() removes all elements contains( value ) returns true if the given element is in the list get( index ) returns the value at the given index indexOf( value ) returns the first index at which the given element appears in the list (or -1 if not found) lastIndexOf( value ) returns the last index at which the given element appears in the list (or -1 if not found) remove( index ) removes value at given index, sliding others back size() returns the number of elements in the list

Copyright 2006 by Pearson Education 13 ArrayList and for loop Recall the enhanced for loop syntax from Chapter 7: for ( : ) { ; } This syntax can be used to examine an ArrayList : int sum = 0; for (String s : list) { sum += s.length(); } System.out.println("Total of lengths = " + sum);

Copyright 2006 by Pearson Education 14 Wrapper classes ArrayList s only contain objects, and primitive values are not objects. e.g. ArrayList is not legal If you want to store primitives in an ArrayList, you must declare it using a "wrapper" class as its type. example: ArrayList list = new ArrayList (); Primitive typeWrapper class intInteger doubleDouble charCharacter booleanBoolean

Copyright 2006 by Pearson Education 15 Wrapper example The following list stores int values: ArrayList list = new ArrayList (); list.add(13); list.add(47); list.add(15); list.add(9); int sum = 0; for (int n : list) { sum += n; } System.out.println("list = " + list); System.out.println("sum = " + sum); Output: list = [13, 47, 15, 9] sum = 84 Though you must say Integer when declaring the list, you can refer to the elements as type int afterward. Java automatically converts between the two using techniques known as boxing and unboxing. index0121 value

Copyright 2006 by Pearson Education 16 Comparable interface reading: 10.2

Copyright 2006 by Pearson Education 17 Natural ordering Many types have a notion of a natural ordering that describes whether one value of that type is "less than" or "greater than" another: int, double : numeric value String : lexical (alphabetical) order Not all types have a natural ordering: Point : How would they be ordered? By y? By x? Distance from origin? ArrayList : What makes one list "less than" another?

Copyright 2006 by Pearson Education 18 Uses of natural ordering An ArrayList of orderable values can be sorted using the Collections.sort method: ArrayList words = new ArrayList (); words.add("four"); words.add("score"); words.add("and"); words.add("seven"); words.add("years"); words.add("ago"); // show list before and after sorting System.out.println("before sort, words = " + words); Collections.sort(words); System.out.println("after sort, words = " + words); Output: before sort, words = [four, score, and, seven, years, ago] after sort, words = [ago, and, four, score, seven, years]

Copyright 2006 by Pearson Education 19 Comparable interface The natural ordering of a class is specified through the compareTo method of the Comparable interface: public interface Comparable { public int compareTo(T other); } Classes such as String and Integer implement Comparable. compareTo returns an integer that is 0, or 0: RelationshipPrimitive comparisonObject comparison less than if (x < y) {if (x.compareTo(y) < 0) { less than or equal if (x <= y) {if (x.compareTo(y) <= 0) { equal if (x == y) {if (x.compareTo(y) == 0) { not equal if (x != y) {if (x.compareTo(y) != 0) { greater than if (x > y) {if (x.compareTo(y) > 0) { greater or equal if (x >= y) {if (x.compareTo(y) >= 0) {

Copyright 2006 by Pearson Education 20 Implementing Comparable You can define a natural ordering for your own class by making it implement the Comparable interface. Comparable is a generic interface, Comparable When implementing it, you must write your class's name in <> after the word Comparable. Example: public class Point implements Comparable You must also write a method compareTo that compares the current object (the implicit parameter) to a given other object. Example: public int compareTo(Point p) {... }

Copyright 2006 by Pearson Education 21 Comparable implementation The following CalendarDate class implements Comparable : public class CalendarDate implements Comparable { private int month; private int day; public CalendarDate(int month, int day) { this.month = month; this.day = day; } // Compares two dates by month and then by day. public int compareTo(CalendarDate other) { if (month != other.month) { return month - other.month; } else { return day - other.day; } public int getMonth() { return month; } public int getDay() { return day; } public String toString() { return month + "/" + day; }