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

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

Embed Size (px)

Citation preview

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

1

Array Lists

Pat Phillips

Craig High School

Janesville, Wisconsin

2005

Page 2: 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

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

3

An array is a fixed-length sequence of values of the same type.

0 1 2 3 4 5 6 7 8 9

16 21 8 37 18 11 27 14 17 12

An array of size N is indexed from zero to N-1

ages

The entire arrayhas a single name

Each value has a numeric index

This array holds 10 values that are indexed from 0 to 9

Arrays – A review

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

4

Arrays – A review

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.

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

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

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

6

Input// filling arrays with consecutive integersfor (count = 0;count < 20;count++){ myArray[count] = count ; }

// filling array from fileint count = 0;while(count < maxCount && !inFile.eof()){ int a = inFile.readInt(); // EasyReader if (!inFile.eof()) { myArray[count] = a;

count++; }

}

Arrays – A review

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

7

Arrays can be instantiated and initialized in one step with an initializer list.

char myGrades[] = {‘A’,‘C’,‘D’};

Arrays – A review

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

16

Array lists

Definitions

Methods

Code Samples

Class projects

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

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.

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

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.

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

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.

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

20

Array Lists

Samples:

ArrayList musicians = new ArrayList( );

ArrayList newFriends = new ArrayList(oldFriends);

ArrayList accounts = new ArrayList(100);

From Java API Docs

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

21

Array Lists

“Sue" “Bob" “Joe"

capacitysize

Automatically keeps track of the list capacity (the length of the allocated array) and list size (the number of elements currently in the list)

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

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

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

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"

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

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

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

25

filling array list using a loop and the Integer wrapper classfor (count = 0;count < 20;count++){

thisList.add(new Integer(count));}filling array list with inputwhile(!infile.eof()) {

int a = input.readInt();//using EasyReaderif (!inFile.eof()){ mylist.add(new Integer(a));}

}

Array Lists

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

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

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

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

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

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.

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

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.

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

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

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

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

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

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

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

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

}

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

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;

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

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()!

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

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)

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

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

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

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