1 Array Lists Pat Phillips Craig High School Janesville, Wisconsin 2005.

Slides:



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

Lists Chapter 4 Carrano, Data Structures and Abstractions with Java, Second Edition, (c) 2007 Pearson Education, Inc. All rights reserved X.
Generics, Lists, Interfaces
1 Various Methods of Populating Arrays Randomly generated integers.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
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.
Chapter 10 Introduction to Arrays
An Array-Based Implementation of the ADT List public class ListArrayBased implements ListInterface { private static final int MAX_LIST = 50; private Object.
Arrays.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
Chapter 9 Introduction to Arrays
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Arrays And ArrayLists - S. Kelly-Bootle
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper Classes Wrapper objects can be.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
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, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 11 Arrays Continued
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
AP Comp Sci A Chapter 12 - Arrays. Ch 12 Goals: Goals: Declare and create arrays Declare and create arrays Access elements in arrays Access elements in.
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.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
IMPLEMENTING ARRAYLIST – Part 2 COMP 103. RECAP  Abstract Classes – overview, details in 2 nd year  Implementing the ArrayList: size(), get(), set()
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Copyright 2008 by Pearson Education Building Java Programs ArrayList Reading: 10.1.
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.
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.
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.
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
GROUPING OBJECTS CITS1001. Lecture outline The ArrayList collection Process all items: the for-each loop 2.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
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.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
int [] scores = new int [10];
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
The ArrayList Data Structure The Most Important Things to Review.
The ArrayList Data Structure Standard Arrays at High Speed!
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Chapter 9 Introduction to Arrays Fundamentals of Java.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
An Array-Based Implementation of the ADT List
TCSS 143, Autumn 2004 Lecture Notes
Can store many of the same kind of data together
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
Can store many of the same kind of data together
Object Oriented Programming in java
int [] scores = new int [10];
ArrayLists 22-Feb-19.
Can store many of the same kind of data together
Arrays.
Presentation transcript:

1 Array Lists Pat Phillips Craig High School Janesville, Wisconsin 2005

2 Objectives A review of arrays An introduction to ArrayList class Method analysis of ArrayList class Manipulating data in array lists Lab practice using array lists with authentic data

3 An array is a fixed-length sequence of values of the same type An array of size N is indexed from zero to N-1 ages The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9 Arrays – A review

4 Declare an array before using. int[] a = new int[5]; This creates an array of integers with a capacity of 5 indexed from 0 to 4. char[] code = new code[100]; This creates an array of characters with a capacity of 100 indexed from 0 to 99.

5 You access array elements with an integer index, using subscript notation as in these assignment statements. a[0] = 78; a[1] = 89; Arrays – A review

6 Input // filling arrays with consecutive integers for (count = 0;count < 20;count++) { myArray[count] = count ; } // filling array from file int count = 0; while(count < maxCount && !inFile.eof()) { int a = inFile.readInt(); // EasyReader if (!inFile.eof()) { myArray[count] = a; count++; } Arrays – A review

7 Arrays can be instantiated and initialized in one step with an initializer list. char myGrades[] = {‘A’,‘C’,‘D’}; Arrays – A review

8 The number of elements an array can hold is accessed by using the length field of the array object: someArray.length for (int x = 0; x < someArray.length ; x++) { System.out.print("\t"+ someArray[x]); } The length is the number of elements the array can hold….not the number of positions filled. Arrays – A review

9 Arrays are often partially filled and you need to remember the number of elements you actually placed in the array. This can be accomplished with a counter. int count = 0; boolean done = false; while(count < maxCount && !done) { System.out.println("Enter integer (-1 to quit.): "); int a = input.readInt(); // EasyReader if (a != -1) { vect[count] = a; count++; } else done = true; } size = count; // Remember number of filled elements } Arrays – A review

10 Arrays can hold primitive values or object references. String[] names = new String[20]; This declaration reserves space to store 20 references to String objects. This does not create the String objects; each object stored must be instantiated independently. Arrays – A review

11 If you run out of room in an array, you must declare a larger array and copy the elements from the original array to the larger array. original new free space Arrays – A review

12 Observe the following code that copies the data from the original array to the new, larger array. int[] newArray = new int[2* original.length]; for (int i = 0; i < original.length; i++) { newArray[i] = original[i]; } original = newArray; Arrays – A review

13 The System class contains several useful class fields and methods. One tool that helps us now is arraycopy. int[] mewArray = new int[2 + original.length]; System.arraycopy(original, 0, newArray, 0, original.length); original = newArray; Arrays – A review

14 An array can be passed as a parameter to a method in its entirety. Because an array is an object, the reference to the array is passed which makes the formal and actual parameters aliases of each other. Because of this, changing any element of the array in the method will change that element in the original also. If a single element of an array is passed to a method it will follow the rules for passing that data type as a parameter. Arrays – A review

15 It is not very convenient to track array sizes and to grow arrays when they run out of space.  If you are collecting objects, use ArrayList.  If you are collecting numbers, make a choice. Which is the least inconvenient? Using wrapper classes and ArrayList ? Tracking array size? Arrays – A review

16 Array lists Definitions Methods Code Samples Class projects

17 Array Lists The ArrayList class is part of the Java standard class library. It provides services similar to arrays. It is part of the Collections API; a group of classes to help organize and manage other objects. The ArrayList class is implemented using an array.

18 Array Lists Unlike arrays, an array list is not declared to store a particular data type. It stores data as an array of Object references. Because of this, primitives must be first stored in a wrapper class to be stored in an array list. You need to remember the type of objects stored in an array list to cast them back to their original type when accessing them.

19 Array Lists The ArrayList class simplifies many of the operations routinely used with arrays such as resizing, inserting and deleting data, and handling exceptions.

20 Array Lists Samples: ArrayList musicians = new ArrayList( ); ArrayList newFriends = new ArrayList(oldFriends); ArrayList accounts = new ArrayList(100); From Java API Docs

21 Array Lists “Sue"“Bob"“Joe" capacity size Automatically keeps track of the list capacity (the length of the allocated array) and list size (the number of elements currently in the list)

22 size() Returns the number of elements in this list. get(int index) Returns the element at the specified position in this list. add(int index, java.lang.Object o) Inserts the object at the specified position in this list. add(java.lang.Object o) Appends (adds) the object to the end of this array list. set(int index, java.lang.Object o) Replaces the element at the specified position in this list with the specified object. Array Lists Method Summaries for accessing and adding data

23 Array Lists “Sue"“Bob"“Joe" capacity When data is added at the end of the array list, the capacity is checked. If it is full it adds space (doubles) and then adds the new data reference to the end. “Jim"

24 Array Lists “Sue"“ Jim "“Bob" capacity When data is added to a spot within the array between existing elements, the capacity is checked. If it is full it adds space (doubles) and then adds the new data reference to the prescribed location and moves everything up one index value. newFriends.add(1, “Jim”); “Joe" New element

25 filling array list using a loop and the Integer wrapper class for (count = 0;count < 20;count++) { thisList.add(new Integer(count)); } filling array list with input while(!infile.eof()) { int a = input.readInt();//using EasyReader if (!inFile.eof()) { mylist.add(new Integer(a)); } Array Lists

26 remove(int index) Removes the element at the specified position from this list. Array Lists Method Summary for deleting data Removes the designated element and moves all others down in index value to fill in the gap. newFriends.remove(0); “Jim"“ Bob "“Joe" “Sue” removed capacity

27 isEmpty () Returns a boolean true if list contains no elements. clear () Removes all elements of the list. contains (java.lang.Object o) Returns true if this list contains the specified object. indexOf (java.lang.Object o) Returns the int value of the index of the first occurrence of the specified object. toString Class method called whenever an ArrayList object is sent to the println method. Array Lists Additional Method Summaries

28 iterator() Returns an iterator over the elements in this list (AB only). listIterator() Returns a list iterator over the elements in this list (AB only). Array Lists Method Summaries for iterating data These methods are tested in the AB test only. They allow for ease in traversing an array list.

29 Array Lists Additional comments: get(i) and set(i) are efficient methods because they allow for random access to elements in the array list. The ArrayList class throws an IndexOutOfBoundsException when i<0 or i  size(). This happens in get(), set(), remove() and add(int, object). Efficiency is a major consideration when choosing between arrays and array lists.

30 Additional comments: Using equals with array lists will use the default Object equals and will compare references not contents. equals returns true if two ArrayList references are the same, false otherwise. Array Lists

31 Array Lists as Parameters to Methods: A method cannot change the size of an array parameter. Why not? A method can change the length of an array list that is passed as a parameter. Why? You can change the contents of the array list but you cannot change the reference. Array Lists

32 Find the largest value in array list named nums Integer large = (Integer)nums.get(0); for (int i = 0; i < nums.size(); i++) { Integer tempLarge=(Integer)nums.get(i); // Notice the casting of the ListArray object to type Integer. if(tempLarge.compareTo(large) > 0) {large = tempLarge; } large.intValue() is the largest int value in the ArrayList

33 Adding the total of values int n2; int total = 0; for (int i =0; i < nums.size(); i++) { Integer n = (Integer)nums.get(i); total += n.intValue(); }

34 Finding a matching object.. Student studentToFind = student1; //could be incoming object parameter of a method for(int i =0; i < school.size(); i++) { Student s = (Student)school.get(i); if (s.equals(studentToFind))return true; } return false;

35 Class Activities Demonstrate array list creation, access and manipulation with real objects before coding. Array Lists 1. Use egg cartons to simulate the array capacity. 2. Cut the carton in half the long way. 3. Fill the first half with a small candy in each spot. 4. When adding the 7th candy element double the size of the array list by placing the second half to the end of the first. 5. Practice methods of ArrayList manipulating the candies. 6. Of course, the last method to practice is clear() !

36 Create projects that use authentic data. Array Lists 1. Search for data-type information on a topic of choice; sport stats, population, land use, tourist data of a specific country or city, transportation data, social demographics.... The list is endless. Online almanacs are a great source of inspiration. 2. Create a class to define the data objects. Example: the BowlGame class might have 6 fields – name, city, team1, team2, score1, score2 3. Add methods such as toString and accessor and modifier methods. (continued)

37 Class Activities Create projects that use authentic data. Array Lists 4. Determine what statistical analysis might be useful and meaningful to generate. Totals? Averages? Greatest? Least? Sorts? Median? 5. Create a menu driven program with methods to load the array list (read from a text file), display data elements, add or delete information, generate statistics and display various results. Write the data back to the file. (Excerpts of an example project are included in these materials.)

38 Summary Both arrays and array lists create indexed storage of data. Arrays are most efficient with primitive data. The ArrayList class offers many methods to simplify creating and manipulating object data. The choice between using arrays or array lists is determined by the type of data to be stored and the operations that must be performed on the data. Creating classroom activities that analyze authentic data reinforces the use of OOD (object-oriented development), teaches valuable statistical analysis, and efficient data storage and retrieval. Array Lists