cs203 lecture 4 john hurley cal state la. memorize this! a data structure is a systematic way to...

21
CS203 LECTURE 4 John Hurley Cal State LA

Upload: arely-couzens

Post on 30-Mar-2015

216 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

CS203 LECTURE 4John Hurley

Cal State LA

Page 2: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

Memorize This!

A data structure is a systematic way to organize information in order to improve the efficiency of algorithms that will use the data

More Data Structures

Page 3: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

So far we have studied arrays and lists, specifically ArrayLists, in detail, and also discussed stacks.

As you know, this class is called "Programming With Data Structures," and obviously, data structures are the main topic of the course. Over the next few weeks, we will introduce a wide array (ha!) of new data structures.

Most of these data structures can be used as collections of wide ranges of parameterized types

We will first learn to use some of the data structure types included with the JDK, then implement one or two on our own, then return to using the built-in ones.

More Data Structures

Page 4: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

4

Java Collection Framework

A collection is a container object that holds a group of objects, often referred to as elements.

The Java Collections Framework supports three types of collections, named sets, lists, and maps.

Page 5: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

5

Java Collection Framework hierarchy, cont.

Set and List are subinterfaces of Collection.

Page 6: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

6The Collection Interface

The Collection interface is the root interface for manipulating a collection of

objects.

Page 7: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

7

ArrayList and LinkedListLike an array, a list stores elements in a sequential order, and allows the user to specify where the element is stored. The user can access the elements by index.

Recall that an array is fixed once it is created. An array is suitable if your application does not require insertion or deletion of elements.

A list can grow or shrink dynamically. ArrayList and LinkedList are the most common concrete implementations of the List interface.

If you need to support random access through an index without inserting or removing elements from any place other than the end, ArrayList offers the most efficient collection. ArrayList is implemented using an underlying array that begins with a default size. If the list outgrows the array, a new array must be created and the contents of the old one copied. Inserting values at arbitrary spots in the list involves moving all the subsequent elements.

If your application requires the insertion or deletion of elements from arbitrary locations in the list, use a LinkedList.

Page 8: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

8

The List Interface, cont.

Page 9: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

9

java.util.ArrayList

«interface» java.util.List<E>

Creates an empty list with the default initial capacity.

Creates an array list from an existing collection.

Creates an empty list with the specified initial capacity.

Trims the capacity of this ArrayList instance to be the list's current size.

+ArrayList()

+ArrayList(c: Collection<? extends E>)

+ArrayList(initialCapacity: int)

+trimToSize(): void

«interface» java.util.Collection<E>

java.util.ArrayList<E>

Page 10: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

10

Linked Lists

A linked list is a data structure consisting of a group of nodes which represent a sequence.

In the simplest form of linked list, each node is composed of a datum and a reference (in other words, a link) to the next node in the sequence. This is called a singlylinked list.

We will learn more about how linked lists are implemented in a few weeks; this week we will use the Java Collections Framework LinkedList<E> class.

Page 11: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

11

Linked Lists

In a doubly linked list, each node contains a reference to the next node anda reference to the previous node.

Either a singly or double linked list may be circular; that is, last nodepoints to the first, and, in a circular doubly-linked list, the first node has a reference to the last

Diagrams from Wikipedia: http://en.wikipedia.org/wiki/Linked_list

Page 12: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

12

Linked Lists Adding and removing elements from any spot in a linked list involves changing, at most, one reference in each of two existing elements and setting, at most, tworeferences in a new element. Compare this to the expense of periodically creating a new array and copying all the elements from an old one.

Add a node to a singly-linked list:

Inserting a node into a doubly linked list just involves also changing the reference from the subsequent element and adding one from the new element back to the previous one

Page 13: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

13

Linked Lists Delete a node from a singly-linked list:

Page 14: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

14

java.util.LinkedList

«interface» java.util.List<E>

Creates a default empty linked list.

Creates a linked list from an existing collection.

Adds the object to the head of this list.

Adds the object to the tail of this list.

Returns the first element from this list.

Returns the last element from this list.

Returns and removes the first element from this list.

Returns and removes the last element from this list.

+LinkedList()

+LinkedList(c: Collection<? extends E>)

+addFirst(o: E): void

+addLast(o: E): void

+getFirst(): E

+getLast(): E

+removeFirst(): E

+removeLast(): E

«interface» java.util.Collection<E>

java.util.LinkedList<E>

LinkedList implements a doubly-linked list. It is a subclass of a hierarchy of List classes, but more importantly it implements the List interface.

Page 15: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

15

package demos;

import java.util.*;

public class TestArrayAndLinkedList { public static void main(String[] args) { List<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(1); // 1 is autoboxed to new Integer(1) arrayList.add(2); arrayList.add(3); arrayList.add(1); arrayList.add(4); arrayList.add(0, 10); arrayList.add(3, 30);

System.out.println("A list of integers in the array list:"); System.out.println(arrayList);

LinkedList<Object> linkedList = new LinkedList<Object>(arrayList); linkedList.add(1, "red"); linkedList.removeLast(); linkedList.addFirst("green");

System.out.println("Display the linked list backward:"); for (int i = linkedList.size() - 1; i >= 0; i--) { System.out.print(linkedList.get(i) + " "); } }}

Page 16: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

16

Linked Lists Based on the info above, you might expect linked lists to be much more efficient than array lists. However, data in a linked list is accessed sequentially; we start at the head of the list and follow the references. This is called traversing the list.

node = list.firstNode while node not null

(do something with node.data) node = node.next

Source for pseudocode: Wikipedia

This may make a linked list less efficient than an array list for operations that require a great deal of traversal, because accessing an array element by index Is efficiently implemented.

Also, memory is allocated on the fly when a node is added. This makes it more likely that different nodes will be far apart in memory, which makes it more expensive to traverse the list.

Page 17: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

17

package listcompare;

public class StopWatch {

private long elapsedTime;

private long startTime;

private boolean isRunning;

public StopWatch() {

reset();

}

public void start() {

if (isRunning) {

return;

}

isRunning = true;

startTime = System.currentTimeMillis();

}

public void stop() {

if (!isRunning) {

return;

}

isRunning = false;

long endTime = System.currentTimeMillis();

elapsedTime = elapsedTime + endTime - startTime;

}

Page 18: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

18

public long getElapsedTime() {

if (isRunning) {

long endTime = System.currentTimeMillis();

return elapsedTime + endTime - startTime;

} else {

return elapsedTime;

}

}

public void reset() {

elapsedTime = 0;

isRunning = false;

}

}

Page 19: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

19package listcompare;

import java.util.ArrayList;

import java.util.LinkedList;

import java.util.List;

import java.util.Random;

public class ListComparer {

Random r = new Random();

public void arrayListSequentialAdds() {

List<Integer> al = new ArrayList<Integer>();

for (int counter = 0; counter < 100000; counter++) {

al.add(0, counter);

//System.out.println(counter);

}

}

public void linkedListSequentialAdds() {

List<Integer> ll = new LinkedList<Integer>();

for (int counter = 0; counter < 100000; counter++) {

ll.add(0, counter);

//System.out.println(counter);

}

}

public void arrayListRandomAdds() {

List<Integer> al = new ArrayList<Integer>();

for (int counter = 0; counter < 100000; counter++) {

al.add(r.nextInt(al.size() + 1), counter);

//System.out.println(counter);

}

}

public void linkedListRandomAdds() {

List<Integer> ll = new LinkedList<Integer>();

for (int counter = 0; counter < 100000; counter++) {

ll.add(r.nextInt(ll.size() + 1), counter);

//System.out.println(counter);

}

}

}

Page 20: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

20

package listcompare;

public class ListDriver {

public static void main(String[] args) {

StopWatch s = new StopWatch();

ListComparer l = new ListComparer();

s.reset();

s.start();

l.arrayListSequentialAdds();

s.stop();

System.out.println("Array List sequential exercise took " + s.getElapsedTime() + " ms");

s.reset();

s.start();

l.linkedListSequentialAdds();

s.stop();

System.out.println("Linked List sequential exercise took " + s.getElapsedTime() + " ms");

s.reset();

s.start();

l.arrayListRandomAdds();

s.stop();

System.out.println("Array List random exercise took " + s.getElapsedTime() + " ms");

s.reset();

s.start();

l.linkedListRandomAdds();

s.stop();

System.out.println("Linked List random exercise took " + s.getElapsedTime() + " ms");

}

}

Page 21: CS203 LECTURE 4 John Hurley Cal State LA. Memorize This! A data structure is a systematic way to organize information in order to improve the efficiency

21

I/O Expense

This is a good time to point out that I/O is very expensive. Rerun the code above with the System.out.println statements uncommented.