Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer...

29
Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    216
  • download

    0

Transcript of Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer...

Page 1: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Dynamic Data Structures and GenericsRecitation – 11/(14,15)/2008

CS 180

Department of Computer Science,

Purdue University

Page 2: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Announcements Project 7: Final Due Wed, Nov. 19 at 10 pm Start early, prefix/jumble search are non-

trivial Mid Term 2 papers ready!! Project 5 grades ready!!

Page 3: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Array List

ArrayList is a class in the standard Java libraries

A dynamically re-sizeable array, so that the total number of elements does not need to be known when created

stores a collection of any type of object

must be all the same type

Page 4: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Array List Why not always use an ArrayList

instead of an array?

1. An ArrayList is less efficient than an array

2. It does not have the convenient square bracket notation.

3. The base type of an ArrayList must be a class type (or other reference type): it cannot be a primitive type.

ArrayList<BaseType> aList = new ArrayList<BaseType>();

Page 5: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Array Lists The following code creates an ArrayList that stores

objects of the base type String with an initial capacity of 20 items:

ArrayList<String> myList = new ArrayList<String>(20);

Specifying an initial capacity does not limit the size to which an ArrayList can eventually grow

Page 6: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Add an Element in ArrayList Add at a specified index

myList.add(2, “Doc”); Add at the end

myList.add(“Dopey”);

Page 7: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Array List Methods The size method is used to find out how

many indices already have elements in the ArrayList

int howMany = myList.size();

The set method is used to replace any existing element, and the get method is used to access the value of any existing element

myList.set(index, "something else");String thing = myList.get(index);

Page 8: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Iterators Iterators provide a general way to traverse

all elements in a collection

ArrayList<String> list = new ArrayList<String>();

list.add("1-FiRsT"); list.add("2-SeCoND"); list.add("3-ThIrD"); Iterator<String> itr = list.iterator(); while (itr.hasNext()) { System.out.println(itr.next().toLowerCase()); }

Page 9: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Linked Data Structures The ArrayList: add and remove methods

operate in linear time because they require a loop to shift elements in the underlying array This is due to contiguous storage in memory.

Linked list overcomes this: Each node in a linked list stores information

and a link to the next node ( and optionally previous node)

This provides the ability to add or remove items anywhere in the list in constant time

Page 10: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Linked List A linked list consists of:

A sequence of nodes

Header

a b c d

Each node contains a value and a link (pointer or reference) to some other node

The last node contains a null link

The list may have a header

Page 11: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Linked List Terminology A node’s successor is the next node in the

sequence The last node has no successor

A node’s predecessor is the previous node in the sequence The first node has no predecessor

A list’s length is the number of elements in it A list may be empty (contain no elements)

Page 12: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Single Linked List in Java

44 97 23 17

myList:

class Node { int value; Node next; Node (int v, Node n) { // constructor

value = v; next = n;}

}

Node n1 = new Node(17, null); Node n2 = new Node(23, n1); Node n3 = new Node(97, n2); Node myList = new Node(44, n3);

Page 13: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Inserting a node in Linked List

321

numerals

2.5node

Find the node you want to insert afterFirst, copy the link from the node that's already in the list

Then, change the link in the node that's already in the list

Page 14: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Delete a Node in Linked List

• To delete the first element, change the link in the header

321

numerals

• To delete some other element, change the link in its predecessor

321

numerals

• Deleted nodes will eventually be garbage collected

Page 15: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Doubly-linked lists

Here is a doubly-linked list (DLL):

Header

null a c nulldb

Each node contains a value, a link to its successor (if any), and a link to its predecessor (if any)

The header points to the first node in the list

Page 16: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Double LL compared to Single LL

Advantages: Can be traversed in

either direction (may be essential for some programs)

Some operations, such as deletion and inserting before a node, become easier

Disadvantages: Requires more

space List manipulations

are slower (because more links must be changed)

Greater chance of having bugs (because more links must be manipulated)

Page 17: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Deleting a node from a DLL Node deletion from a DLL involves changing two links

Deletion of the first node or the last node is a special case

Garbage collection will take care of deleted nodes

Header

null nulla b c

Page 18: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Inner Classes All the classes so far have been “top level”

classes It is possible (and useful) to define a class

inside another class Sometimes you want a class C2 that will

only be used only by class C1. It might be handy to be able to include the

definition of C2 in the file defining C1. Inner classes can be very useful, especially

with AWT (GUI) event handling.

Page 19: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Inner Classes Exampleclass Outer {

int n;class Inner {

int ten = 10;void setNToTen ( ) { n = ten; }

}void setN ( ) {

new Inner( ).setNToTen ( );}

}

Page 20: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Generics Motivation In Java, array elements must all be of the

same type: int[] counts = new int[10];

Hence, arrays are type safe: The compiler will not let you put the wrong kind of thing into an array

A collection, such as a Vector or the non-parameterized ArrayList, cannot hold primitives, but will accept any type of Object: ArrayList someStuff = new ArrayList();

someStuff.add("A String is an Object");someStuff.add(10);

Is not type safe; Making a collection type safe is a tedious process

Page 21: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Generics J2SE 5.0 provides compile-time type safety with

the Java Collections framework through generics

Generics allows you to specify, at compile-time, the types of objects you want to store in a Collection. Then when you add and get items from the list, the list already knows what types of objects are supposed to be acted on

So you don't need to cast anything. The "<>" characters are used to designate what type is to be stored. If the wrong type of data is provided, a compile-time exception is thrown.

Page 22: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Generics Example Example (compile-time exception):

import java.util.*; public class First {

public static void main(String args[]) { ArrayList<Integer> myList = new ArrayList<Integer>(10); myList.add(10); // Autoboxing converted the int type to an

Integer myList.add("Hello, World");

} }

First.java:7: cannot find symbol symbol : method add(java.lang.String) location: interface java.util.List<java.lang.Integer> myList.add("Hello, World"); ^ 1 error

Page 23: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Question 2public class Exam{

private int x;public Exam() {x = 0;}public Exam(int x) {setX(x);}public Exam(Exam e) {x = e.getX();}public int getX() {return x + 10;}public void setX(int x) {this.x = x;}public void modifyX(Exam e) {this.x = e.getX() + 10;}

public static void main(String[] args) {Exam e1 = new Exam();Exam e2 = new Exam(e1);e2.modifyX(e1);System.out.println(e1.getX() + "::" + e2.getX());}

}

Q2. If X is static(a) No change(b) 10::10(c) 40::40(d) 30::30

Page 24: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Question 4

Q4. Which of the following statements about Java’s wrapper classes is FALSE?

(a) They provide utility methods for their primitive counterparts.

(b) They facilitate information hiding by adding a layer of indirection.

(c) They have no default constructor.(d) They do not provide modifier methods.

Page 25: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Question 10public class Parent{

private void f() {System.out.print("parent f()"); }

public static void main(String[] args) {Parent p = new Derived();p.f();}}

class Derived extends Parent{public void f() {System.out.print("derived f()");}}

(a) parent f() derived f()(b) parent f()(c) derived f()(d) derived f() parent f()

Page 26: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Question 12public class Question12{public void method(Object o) {System.out.print("Object Verion");}

public void method(String s) {System.out.print("String Version");}

public static void main(String args[]) {Question12 q = new Question12();q.method(null);}}

(a) String Version(b) There is no output due to null pointer Exception(c) There is no output due to compile time error(d) Object Version

Page 27: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Question 19public class Call{private int var;public Call (int var) { this.var = var; }public void Exchange (Call arr1, Call arr2) {Call temp = arr1;arr1 = arr2;arr2 = temp;}

public static void main (String[] args) {Call[] arr = new Call[3];for (int i = 0; i < arr.length; ++i)arr[i] = new Call(i + 1);arr[0].Exchange(arr[1], arr[2]);for (int i = 1; i < arr.length; i++)System.out.print(arr[i].var); } }

(a) 32(b) 64(c) 23(d) 46

Page 28: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Question 20public class Base {public void Print () {System.out.print("Red");} }

public class FirstDerived extends Base {

public void Print () {System.out.print("Blue");} }

public class SecondDerived extends Base

{public void Print (String str) {System.out.print("Green"); }}

public class Dynamic{public static void main (String[] args) {

Base[] b = new Base[2];b[0] = new FirstDerived();b[1] = new SecondDerived();b[0].Print();b[1].Print();}}

OUTPUT: BlueRed

Page 29: Dynamic Data Structures and Generics Recitation – 11/(14,15)/2008 CS 180 Department of Computer Science, Purdue University.

Quiz Show the Linked List formed at the end of this

program class Node { int value;

Node next; Node (int v, Node n) { // constructor

value = v; next = n;}

public static void main(String args[]) {

Node n1 = new Node(13, null); Node n2 = new Node(17, n1); Node n3 = new Node(29, n2); n1.next = n3; }