0% found this document useful (0 votes)
4 views30 pages

L14 Arraylists IntroGenerics B (Ch11)

This document covers advanced topics in Java programming, specifically focusing on ArrayLists and generics. It discusses iterating over ArrayLists, useful methods, and the implementation of generics to enhance type safety in collections. Additionally, it includes practical examples and comparisons of different methods for manipulating ArrayLists, as well as the concept of auto-boxing with primitive types.

Uploaded by

ymkbthz5yr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views30 pages

L14 Arraylists IntroGenerics B (Ch11)

This document covers advanced topics in Java programming, specifically focusing on ArrayLists and generics. It discusses iterating over ArrayLists, useful methods, and the implementation of generics to enhance type safety in collections. Additionally, it includes practical examples and comparisons of different methods for manipulating ArrayLists, as well as the concept of auto-boxing with primitive types.

Uploaded by

ymkbthz5yr
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

ArrayLists and Intro to Generics

Part 2/2

Dr. Mostafa Mohamed

Acknowledgement: The slides mainly rely on the textbook of Y. D. Liang titled “Introduction to
Java Programming, 10th Ed.”, Pearson Edu. Inc. COSC 121. Page 1
Outline
Previously:
▪ Intro to Java Collection Framework
▪ The ArrayList Class
▪ Implementing a Stack using ArrayList
▪ Sample applications
Today:
▪ Iterating Over an ArrayList
▪ Random Access in ArrayLists
▪ Useful Methods for Lists
• Arrays and Collections classes

▪ Intro to Generics COSC 121. Page 2


Iterating Over an ArrayList

COSC 121. Page 3


Iterating Over an ArrayList
You can iterate over this array in different ways:

Using the index

Using for-each

Using an iterator.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 4
Iterators and ArrayList
An ArrayList (and each collection) is Iterable. You can
obtain its Iterator to traverse all its elements.

Two more useful methods in ArrayList:


▪ iterator()
▪ listIterator()
Iterators and ArrayList, cont.
iterator(): returns an iterator object
▪ The iterator object implements the Iterator interface.
▪ Methods:
• hasNext(): Returns true if this iterator has more elements to traverse.
• next(): Returns the next element from this iterator.
• remove(): Removes the last element obtained using the next method.
0 1 2 3 0 1 2 3
next()

Iterator Iterator

0 1 2 3 0 1 2
remove()

Iterator Iterator
Iterators and ArrayList, cont.
listIterator(): returns a ListIterator object
▪ ListIterator is a subtype of Iterator
▪ Methods:
• next(), previous()
• hasNext(), hasPrevious()
• remove()
• nextIndex(), previousIndex() returns the next/previous index

0 1 2 3

ListIterator

previous() next()
hasPrevious() hasNext()
previousIndex() nextIndex()
COSC 121. Page 7
Iterators and ArrayList, cont.
listIterator() also allows initializing the iterator with an
index
▪ To position the iterator some place other than the beginning of
the list.

ListIterator x = list.listIterator( 0); //same as no arg


ListIterator y = list.listIterator(2);
ListIterator z = list.listIterator(list.size());

0 1 2 3

x y z

COSC 121. Page 8


Iterators and ArrayList, cont.
ListIterator.add():inserts just before the iterator.
ListIterator.set():replaces last element returned by next or previous
ListIterator<String> it;
ArrayList<String> list = new ArrayList<>(Arrays.asList("A","B","C","D"));
it = list.listIterator(1); A B C D
it

it.add("X"); A X B C D
it

it.add("Y"); A X Y B C D
it

it.previous(); A X Y B C D
it

it.set("Z"); A X Z B C D
it

It.set("W"); A X W B C D
it COSC 121. Page 9
Practice 4
Find the sum of all elements in array list, nums, using three
different ways (loops).
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4));

//using for-i loop


int sum = 0;
for (int i = 0; i < list.size(); i++)
sum += list.get(i);

//using for-each loop


sum = 0;
for (int item : list)
sum += item;

//using iterator
sum = 0;
Iterator<Integer> it = list.iterator();
while(it.hasNext())
sum += it.next();
COSC 121. Page 10
Practice 5
Use a ListIterator to print all elements in an ArrayList in
forward direction then in backward direction.
▪ e.g., for [3, 2, 6, 9], the output would be:
Elements in forward direction: 3 2 6 9
Elements in backward direction: 9 6 2 3
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(3,2,6,9));

ListIterator<Integer> it = list.listIterator();

//forward printing
while(it.hasNext())
System.out.print(it.next() + " ");

System.out.println();

//backward printing
while(it.hasPrevious())
System.out.print(it.previous() + " ");
COSC 121. Page 11
Practice 6
Use a ListIterator to print all elements in an ArrayList in
backward direction.
▪ e.g., for [3, 2, 6, 9], the output would be 9 6 2 3

ArrayList<Integer> list = new ArrayList<>(Arrays.asList(3,2,6,9));

ListIterator<Integer> it = list.listIterator(list.size());

//backward printing
while(it.hasPrevious())
System.out.print(it.previous() + " ");

COSC 121. Page 12


Removing all A’s
Suppose ArrayList x has 4 strings ["A","A","B","A"].
Write code the will remove all A’s.

Efficient?
Solution 1:
while(x.contains("A"))
x.remove("A");

Solution 2: Efficient?

Iterator <String> it = x.iterator();


while(it.hasNext())
if(it.next().equals("a"))
it.remove();
Argument must be a Collection
Solution 3:
x.removeAll( Arrays.asList("A") );
COSC 121. Page 15
Experiment
final int N = 20000; //try other values
//create an arraylist initialized to random chars then "a"s
ArrayList<String> list1 = new ArrayList<>(N);
for(int i = 0; i<N; i++)
if(i<N/2) list1.add((char)(Math.random()*25+'b')+""); //random characters
else list1.add("a");
//create a second arraylist identical to list1
ArrayList<String> list2=(ArrayList<String>)list1.clone();

//***Remove all "a"s and measure the time ***


//method 1: using contains()
long start = System.currentTimeMillis();
while(list1.contains("a")) //search for a
list1.remove("a"); //search for a, then remove a
long end = System.currentTimeMillis();
System.out.printf("Method 1 Time: %d ms\n",(end-start));

//method 2: using an iterator


start = System.currentTimeMillis();
Iterator<String> it = list2.iterator(); Output
while(it.hasNext()) Method 1 Time: 1269 ms
if(it.next().equals("a")) Method 2 Time: 9 ms
it.remove(); //remove a
end = System.currentTimeMillis();
System.out.printf("Method 2 Time: %d ms\n", (end-start));
COSC 121. Page 16
Random Access in ArrayList

COSC 121. Page 17


ArrayList Supports Random Access
Arraylists are implemented using arrays.
▪ Whenever the current array cannot hold new elements in the
list, a larger new array is created to replace the current array.
• Illustration: http://cs.armstrong.edu/liang/animation/web/ArrayList.html

Arrays use an index to reference its elements


memory address
0
1 int[] list = new int[6];
2
… . list [index] = list address + index
list . list[0] = list address
index 0 element 0 Assuming
.
1 element 1 . list[1] = list address + 1 1 int = 1
Consecutive
Memory Space … … . memory
. block
Reserved 5 element 5 list[5] = list address + 5
.

COSC 121. Page 18


Experiment

//create and initialize an arraylist


ArrayList<String> list = new ArrayList<>(20000);
for(int i = 0; i<list.size(); i++)
if(i<N/2) list.add((char)(Math.random()*25+'b')+"");
else list.add("a");

//***Visiting all elements***


//method 1: using get(index), O(n)
long start = System.currentTimeMillis();
for(int i = 0; i<list.size(); i++)
list.get(i); // random access – very efficient!
long end = System.currentTimeMillis();
System.out.printf("Method 1 Time: %d ms\n",(end-start));

//method 2: using an iterator, O(n)


start = System.currentTimeMillis();
Iterator<String> it = list.iterator(); Output
while(it.hasNext()) Method 1 Time: 2 ms
it.next(); Method 2 Time: 2 ms
end = System.currentTimeMillis();
System.out.printf("Method 2 Time: %d ms\n",(end-start));

COSC 121. Page 19


Useful Methods for Lists
(Arrays and Collections classes)

COSC 121. Page 20


Array ↔ ArrayList
Array → ArrayList
• Creating an ArrayList from an array:
• Syntax: list = Arrays.asList(array)

ArrayList → array
• Creating an array from an ArrayList:
• Syntax: list.toArray(array);

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 21
java.util.Collections methods
Collections.sort (if elements are comparable):

Collections.min or .max

Collections.shuffle

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 22
Intro to Generics

COSC 121. Page 23


Generics
A generic class has at least one member of an unspecified type.

ArrayList is a generic class with a generic type E


▪ We have also seen generics before, e.g., the Comparable interface.
class Robot implements Comparable<Robot>
▪ The type(s) you provide on instantiation appear in the API as single
letters in angle brackets after the name of the class, e.g.
ArrayList<E>.

All collections support generic (or parameterized) types to


indicate what type is stored in the collection.
It is better to precisely specify the type of objects in a collection
so that the compiler can check for errors.
▪ If you don’t, then a collection can store any type of object as
all objects are a subclass of Object.

COSC 121. Page 24


Object Wrapper Classes
The generic type E must be
reference type.
▪ You cannot replace a generic type with
a primitive type such as int, double, or
char.
For example, the following statement
is wrong:
ArrayList<int> a = new ArrayList<>(); // X
To create an ArrayList object for int
values, you have to use:
ArrayList<Integer> a =new ArrayList<>(); //✓

Java employed object wrappers,


which 'wrap around' or encapsulate
all the primitive data types and allow
them to be treated as objects.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 25
But, how am I still able to insert primitives into a list?
If you have
ArrayList<Double> a = new ArrayList<>();
You can add an double value to a. For example,
a.add(5.5);
Java automatically wraps 5.5 into new Double(5.5). This is
called auto-boxing

Examples:
list.add(5.5); // 5.5 is automatically converted to new Double(5.5)

list.add(3.0); // 3.0 is automatically converted to new Double(3.0)

Double doubleObj = list.get(0); // No casting, returns Double

double d = list.get(1); // Automatically converted to double


Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 26
Index or Value-of-Item??
When using generics, exact PARAMETER MATCHING takes
precedence over AUTO-BOXING

Consider this code below:


ArrayList<Integer> list = new ArrayList<>();
list.add(3); //ok, auto-boxing used for 3
list.add(0,9); //ok, auto-boxing used for 9
list.remove(9); //ERROR. 9 is not valid index
▪ Why 9 is considered an index but not a value?
• That is because exact parameter matching tells Java that 9 as an int
matches remove(int index) - but not remove(Object value), and therefore
it doesn’t try to ‘auto-box’ 9 in an Integer class and simply assumes 9 is
an index.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 27
Defining Generic Classes and Interfaces
Define a generic class Generic Robot that has two attributes:
▪ One instance variable of the generic type
▪ One instance variable of the generic array type

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 31
Defining Generic Classes and Interfaces
You have seen before how to create MyStack class that holds
instances of the type Object, which means any type (you can
store cars, apples, and humans in the same stack).

To force MyStack to accept only a certain type of objects, you


two options:
▪ 1) to create individual classes for each type (e.g., HumanStack,
AppleStack, CarStack, etc) – bad approach!!

▪ 2) to create a generic class, GenericStack<E>, where E is


replaced by the required type when creating an instance of the
class.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 32
Defining Generic Classes and Interfaces

GenericStack<E>
-list: ArrayList<E> A list to store elements.
+GenericStack() Generates an empty stack
+getSize(): int Returns the number of elements in this stack.
+peek(): E Returns the top element in this stack.
+pop(): E Returns and removes the top element in this stack.
+push(o: E): void Adds a new element to the top of this stack.
+isEmpty(): boolean Returns true if this stack is empty.

Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. COSC 121. Page 33
Defining Generic Classes and Interfaces
public class MyStack<E> {
private ArrayList<E> list = new ArrayList<>();

public int size() {return list.size();}


public boolean isEmplty() {return list.isEmpty();}

public void push(E e) {list.add(e);}


public E pop() {
return size()>0? list.remove(list.size()-1):null;
}
public E peek(){
return size()>0? list.get(list.size()-1):null;
}

public static void main(String[] args) {


MyStack<String> stack = new MyStack<>();
stack.push("A"); stack.push("B");
System.out.println(stack.peek());
}
} COSC 121. Page 34
What to know more about Generics?
There is a lot more to discuss about Java Generics. However,
they are outside the scope of this course.
More can be found in
▪ Chapter 19 of the textbook
▪ COSC 222: Data Structures

COSC 121. Page 35

You might also like