CompSci 230 S2 2017
Programming Techniques
ArrayLists
Agenda & Reading
Topics:
Introduction to Collections and Class ArrayList
ArrayLists
ArrayList with Generics
Wrapper Classes
ArrayLists Vs Arrays
Reading
Java how to program Late objects version (D & D)
Chapter 6
The Java Tutorial
ArrayLists
http://www.tutorialspoint.com/java/java_arraylist_class.htm
2 Lecture07
1.Introduction
Introduction to Collections and Class ArrayList
Collections provide efficient methods that organize, store
and retrieve your data without requiring knowledge of how
the data is being stored.
ArrayLists:
Everything stored must be an Object (non-primitive data types)
Objects can be different types
provides methods for adding and removing
keeps track of the list capacity (the length of the allocated array)
and list size (the number of elements currently in the list)
Example: capacity
import java.util.ArrayList; size
...
ArrayList list = new ArrayList(); "Cat" "Hat" "Bat"
... ...
3 Old Lecture07
version
2.ArrayLists
Advantages & Disadvantages
Advantages:
Size is dynamic, rather than fixed.
Disadvantages:
Less efficient than arrays
Lacks familiar [ ] syntax (Java limitation, supported by C+
+)
Base type must be an object (not primitive) type
4 Lecture07
2.ArrayLists
Methods
5 Lecture07
2.ArrayLists
Methods to add elements
Only objects can be added to an ArrayList.
public boolean add(Object x)
list.add( "One" ); One Two Three
list.add( "Two" );
list.add( "Three" );
Adds an object to the end of the list, adjusts the size of the list; returns
true
Objects can be added to a specific position in an ArralyList:
public void "One"
list.add( add(int
); index, Object o)
One Fred Two Thre
list.add( "Two" ); e
list.add( "Three" );
list.add( 1, "Fred" );
Inserts x at position index, sliding elements at position index and higher to
the right (adds 1 to their indices) and adjusts size.
Capacity increases if necessary
6 Lecture07
2.ArrayLists
Search methods
public boolean contains (Object target )
True if ArrayList contains target; false otherwise.
true
System.out.println(list.contains("Three" ));
public int indexOf (Object target )
Returns index of first occurrence of target in ArrayList; -1
otherwise.
int i = list.indexOf("Fred" ); 1
public int lastIndexOf (Object target )
Same as above except index of last occurrence is returned.
7 Lecture07
2.ArrayLists
Size & Capacity
public boolean isEmpty ( )
True if empty; false otherwise.
System.out.println(list.isEmpty()); false
public int size ( )
Returns number of elements in ArrayList
System.out.println(list.size());
4
public void clear ( )
Removes all elements; size() becomes 0
list.clear();
8 Lecture07
2.ArrayLists
Methods to remove elements
Object remove(int index) One Fred Two Thre
e
where 0<=index<size() (or exception) Fred Two Thre
e
Removes element at index; shifts to the left remaining
elements at index+1 … size()-1.
list.remove( 0 ); String s = (String) list.remove( 0 );
System.out.println(s); One
boolean remove(Object theElement)
if found then removes the first occurrence of theElement;
shifts the remaining elements to the left; size() becomes
size()-1; returns true. One Fred Two Thre
e
ifboolean
not found then returns false.
n = list.remove("Three");
System.out.println(n);
One Fred Two
true
9 Lecture07
2.ArrayLists
Array-like methods
public Object set ( int index, Object newElement )
where 0<=index<size() (or exception)
Replaces the element at index with a newElement and
returns the element formerly at the specified
One position.
Fred Two
System.out.println(list.set(0, "Hello"));
One
Hello Fred Two
System.out.println(list.set(4, "Good"));
Exception in thread "main"
public Object get ( int index ) java.lang.IndexOutOfBoundsException:
where 0<=index<size() (or exception)
Returns the element at index.
Hello Fred Two
Hello
System.out.println(list.get(0));
System.out.println(list.get(4)); Exception in thread "main"
10 java.lang.IndexOutOfBoundsException: Lecture07
2.ArrayLists
Methods to print the list
public String toString() Hello Fred Two
Returns a String which contains all the object in the
ArrayList
System.out.println(list.toString()); [Hello, Fred, Two]
Hello
Using
for( int a For
i=0; loop
i<list.size(); i++ ) { Fred
System.out.println(list.get(i).toString()); Two
}
11 Lecture07
2.ArrayLists
Equality
public boolean equals ( Object other )
True only when both are of the same size, and both have
the same elements with the same order.
list.add("Hello");
list.add("Two"); false
list.add("Fred");
myList2.add("Two");
myList2.add("Hello");
myList2.add("Fred");
System.out.println(list.equals(myList2));
12 Lecture07
2.ArrayLists
Different Types Old
version
Stored elements may be of different types
Example: Objects of type Integer, Character and Point
could all be stored in ArrayList. (Object is a superclass of
Integer, Character and Point.myList2.clear();
Therefore, all are of type
Object) myList2.add(new Integer(5));
myList2.add(new Character('c'));
[5, c, java.awt.Point[x=10,y=20]]
myList2.add(new Point(10,20));
System.out.println(myList2);
Need to be concerned about type returned by
ArrayList method.
Notice: Return type for get, set and remove are of type
Integer i = (Integer) myList2.get(0);
System.out.println(i);
Object. If the Point
returned object
p = (Point) is to be used
myList2.get(2); 5 with a particular
System.out.println(p);
class, it needs to be cast to that class type. java.awt.Point[x=10,y=20]
13 Lecture07
Exercise 1
What is the output of the following code fragment?
ArrayList list = new ArrayList();
Point pt1 = new Point(3, 4);
list.add( pt1 );
Point pt2 = (Point) list.get( 0 );
pt2.x = 23;
if ( pt2 == pt1 ) {
System.out.println( "Same object" );
} else {
System.out.println( "Different object" );
}
System.out.println();
14 Lecture07
3.Generic ArrayLists
Starting with Java 5, ArrayList<T> and other collection classes
hold objects of a specified data type.
The T (by convention) is a placeholder—when declaring a new
ArrayList, replace it with the type of elements that you want the
ArrayList to hold.
Classes with this kind of placeholder that can be used with any type
are called generic classes.
The elements’ data type is shown in angle brackets and
becomes part ofwords
ArrayList<String> the =ArrayList type. For example:
new ArrayList<String>();
ArrayList<Integer> nums = new ArrayList<Integer>();
ArrayList<String> appears in the variable declaration and in the
class instance creation expression.
Using <> in a class instance creation expression tells the compiler to
determine what belongs in the angle brackets.
15 Lecture07
L07Code02.jav
3.Generic ArrayLists a
Adding elements & for-each loop
Adding elements: [One, Two, Three]
ArrayList<String> words = new ArrayList<String>();
words.add("One");
words.add("Two");
words.add("Three");
System.out.println(words);
Enhanced for Statement
The for-each loop is used to access each successive value
in a collection of values.
Syntax: forStatement;
(Base_Type var :Collection_Object)
Elements are
Example: all in the same Standard for-
type. loop
for (String str : words)
System.out.println(str); for( int i=0; i<words.size(); i++ )
System.out.println( words.get( i ));
16 Lecture07
4.Wrapper Classes
Each primitive data type has a corresponding
Wrapper class.
Java’s primitive data types (boolean, int, etc.) are not
classes.
Wrapper classes are used in situations where objects are
Data Type Wrapper
required.
boolean Boolean
The
char wrapper class can be used to convert a primitive into
Character
an
byteobject type.
Byte
short Short
int Integer
long Long
float Float
double Double
17 Lecture07
4.Wrapper Classes
Value => Object: Wrapper Object Creation
Wrapper.valueOf() takes a value (or string) and
returns an object of that class:
Integer i1 = Integer.valueOf(42);
Integer i2 = Integer.valueOf("42");
Boolean b1 = Boolean .valueOf(true);
Boolean b2 = Boolean .valueOf("true");
Using object creation:
Integer i1 = new Integer(42);
Character cC = new Character('b');
Boolean bB = new Boolean(true);
18 Lecture07
4.Wrapper Classes
Object => Value & String => value
Each wrapper class Type has a method typeValue to
obtain the object’s value: intValue(), doubleValue(),
charValue() etc
System.out.println(i1.intValue()); 42
System.out.println(c1.charValue()); b
System.out.println(b1.booleanValue()); true
It also has a method parseType() to parse a string
representation & return the literal value.
Integer.parseInt("42") => 42
Boolean.parseBoolean("true") => true
Double.parseDouble("2.71") => 2.71
19 Lecture07
4.Wrapper Classes
Auto boxing
Since Java 5, conversion from int to Integer and from
double to Double is, in most cases, automatic
(autoboxing/autounboxing)
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(12);
numbers.add(5); autoboxing
int sum = 0;
for (int i : numbers) {
sum += i; autounboxing
}
System.out.println("Total=" + sum);
20 Lecture07
Exercise 2
What is the output of the following code fragment?
ArrayList<Integer> x = new ArrayList<Integer>();
x.add(3);
x.add(5);
x.add(8);
x.add(9);
ArrayList<Integer> y = new ArrayList<Integer>();
y.add(6);
y.add(7);
y.add(1);
y.add(2);
for (int i=0; i<x.size(); i++) {
x.set(i, y.get(i));
y.set(i, x.get(i));
}
System.out.println(x);
System.out.println(y);
21 Lecture07
5.ArrayLists Vs Arrays
Capacity:
Array: Once you set the array size, you cannot change it easily.
int actualSize = . . .;
Point[] points1 = new Point[actualSize];
ArrayList: It automatically adjusts its capacity as you add and remove
Initial capacity
elements, without your needing to write any code. = 10
ArrayList<Point> points2 = new ArrayList<Point>();
If the internal array is full, the array list automatically creates a bigger array
andArrayList<Point>
copies all the objects
points2from theArrayList<Point>(100);
= new smaller to the bigger array.
capacity = 100
Printing the entire array/ArrayList:
System.out.println(points1); [Ljava.awt.Point;@659e0bfd
Array : print the memory address only
ArrayList: print the entire list [java.awt.Point[x=1,y=2],
System.out.println(points2);
22 java.awt.Point[x=3,y=4]] Lecture07
5.ArrayLists Vs Arrays
Capacity
Distinction between the capacity
array: new Point[100]; // size is 100
If you allocate an array with 100 entries, then the array has 100 slots, ready
for use. new ArrayList<Point>(100); // capacity is 100
ArrayList:
An array list with a capacity of 100 elements has the potential of holding
100 elements (and, in fact, more than 100, at the cost of additional
reallocations);
At the beginning, even after its initial construction, an array list holds no
elements at all.
points1.length
Actual number of elements inside the array/ArrayList
array:
returns thepoints2.size()
actual number of elements in the array
ArrayList:
returns the actual number of elements in the ArrayList
23 Lecture07
5.ArrayLists Vs Arrays
Accessing Elements
To access or change the element:
Array: points1[i] = new Point(1,2);
Use [] syntax to access or change the element of an array
ArrayList: points2.set(i, new Point(1,2));
Use the get and set methods to access or change the element in the ArrayList
Note: Do not call list.set(i, x) until the size of the ArrayList is larger than i.
Use the add method instead of set to fill up an array, and use set only to replace a
previously added element.
To get an element
Point p = points1[i];
Array: After Java SE
5.0
ArrayList: Point p = points2.get(i);
Before Java SE 5.0, there were no generic classes, and the get method of the raw ArrayList
class had no choice but to return an Object.
Consequently, callers of get had to cast the returned value to the desired type:
Before Java SE
Point p = (Point) points2.get(i); 5.0
The raw ArrayList is also a bit dangerous. Its add and set methods accept objects of any
type and you run into grief only when you retrieve the object of another type and try to
cast it.
24 Lecture07
5.ArrayLists Vs Arrays
Converting between Array and ArrayList
Array to ArrayList java.awt.Point[x=1,y=2]
Use the asList() method in the Arrays class java.awt.Point[x=3,y=4]
Point[] points1 = {new Point(1,2), new Point(3,4)};
ArrayList<Point> points2 = new
ArrayList<Point>(Arrays.asList(points1));
for (Point p: points2)
System.out.println(p);
Note: The Arrays class provides static methods for common
array manipulations. For example:
sort() - for sorting an array
equals() for comparing arrays
fill() for placing values into an array
ArrayList to Array
Use the toArray() method from the ArrayAList class
String[] copy = new String[words.size()]; One
copy = words.toArray(copy); Two
for (String i: copy) Three
System.out.println(i);
25 Lecture07
Exercise 3
Write a static method to get distinct elements from an
array. The method returns an ArrayList which
contains
int[] distinct
numbers = {25, 2, 5, 9,elements.
10, 15, 8, 2, 5, 9}; [25, 2, 5, 9, 10, 15, 8]
System.out.println(getUnique(numbers));
public static ArrayList<Integer> getUnique(int[] source) {
//create ...
for (int value: source) {
}
return uniqueList;
}
26 Lecture06