82
[8-1] Programming in Java Java Tool Packages(2 ) Lecture8

[8-1] Programming in Java Java Tool Packages (2) Lecture8

Embed Size (px)

Citation preview

Page 1: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-1]Programming in Java

Java Tool Packages(

2)

Lecture8

Page 2: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-2]Programming in Java

Object

Date

Random

BitSet

Dictionary

Stack

Observable

StringTokenizer

Enumeration

Properties

Hashtable

Vector

Observer

Java.lang.Cloneable

Standard Utilities in Java 1.1

Page 3: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-3]Programming in Java

(1) BitSet class

• A BitSet is a set of true and false bits with a size of 2 32

-1, all bits initially false

• The storage size of the set is only large enough to hold the highest bit index set to true or cleared to false — any bits beyond that are assumed to be false

(2) Constructors

• BitSet() or BitSet(int nbits)

(3) Methods• public void set(int pos) • public void clear(int pos)

BitSet(1)

Page 4: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-4]Programming in Java

• public boolean get(int pos)

• public void and(BitSet other) • public void or(BitSet other)• public void xor(BitSet other) • public int size() • public int hashCode() • public boolean equals(Object other)

(3) Example

• Example1: Using a BitSet to mark which characters occur in a string

• Example2: Using a BitSet to demonstrate the sieve of Eratosthenes

BitSet(2)

Page 5: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-7]Programming in Java

Enumeration

• Most collection classes use the Enumeration interface as a means to iterate through the values in the collection

• Each such class has one or more methods to return an Enumeration object

(1) Methods

• public abstract boolean hasMoreElements()

Return true if the enumeration contains more elements

• public abstrat Object nextElement()

Returns the next element of the enumeration

Throws NoSuchElementException if no more elements exits

Enumeration Interface

Page 6: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-8]Programming in Java

import java.util.Enumeration;

class Enum implements Enumeration {

private int count = 0;

private boolean more = true;

public boolean hasMoreElements() { return more; }

public Object nextElement() {

count++;

if (count >4 ) more = false;

return new Integer(count); }}

Enumeration enum = new Enum();

while (enum.hasMoreElements())

System.out.println(enum.nexElement());

Example

Page 7: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-9]Programming in Java

• Vector

The vector class provides a resizeable array of Object.

Items can be added to the beginning, middle,or end of a vector, and any element in the vector can be accessed with an array index

• Constructor public Vector(int initialCapacity,int capacityIncrement) public Vector(int initialCapacity): Vector(initialCapacity,0)

public Vector() //Vector(10,10)

• Fields    protected Object elementData[] protected int elementCount protected int capacityIncrement

Vector

Page 8: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-10]Programming in Java

• public final synchronized void setElementAt(Object obj, int in

dex)

• public final synchronized void removeElementAt(int index)

• public final synchronized void insertElementAt(Object obj, in

t index)

• public final synchronized void addElement(Object obj)

• public final synchronized boolean removeElement(Object obj)

• public final synchronized void removeAllElements()

Modification Methods

Page 9: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-11]Programming in Java

import java.util.Vector;

public class Polygon{ // 存储多边形顶点的 Point 表 private Vector verties = new Vector();

public void add(Point p){ verties.addElement(p); }

public void remove(Point p){ verties.removeElement(p); }

public int numVerties(){ return verties.size(); }

// .. 其它方法 ....

Example

Page 10: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-12]Programming in Java

All methods that search the vector for an element use Object.equals to compare the object being searched for the elements of the Vector

• public final synchronized Object elementAt(int index)

• public final boolean contains(Object obj)

• public final synchronized int indexOf(Object obj ,int index)

• public final int indexOf(Object obj): =indexOf(obj,0)

• public final synchronized int lastIndexOf(Object obj ,int index)

• public final int lastIndexOf(Object obj): =lastIndexOf(obj , 0)

• public final synchronized void copyInfo(Object[] anArray)

• public final synchronized Enumeration element()

• public final synchronized Object firstElement()

• public final synchronized Object lastElement()

Detection Methods

Page 11: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-13]Programming in Java

• public final int size()

• public final boolean isEmpty()

• public final synchronized void trimToSize() *capacity=size

• public final synchronized void setSize(int newSize)

• public final int capacity()

• pub final synchronized void ensureCapacity(int minCapacity)

(6) Example // 使 Polygon 能包含另一个多边形的顶点的方法 public void merge(Polygon other){

int otherSize = other.vertices.size();

vertices.ensureCapacity(vertices.size()+otherSize);

for(int i=0;i<otherSize;i++)

vertices.addElement(other.vertices.elementAt(i)); }

Capacity Methods

Page 12: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-14]Programming in Java

Array vs. Vector

(1) Function• Array: primitive type data;consistent type; size

fixed; less operation• Vector:object;uncertain size; heterogeneous; more

operation

(2) Access elemnet• Array: x = a[i]; a[i] = x;• Vector: x= v.elementAt(i); v.setElementAt(x,i)

Page 13: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-15]Programming in Java

The stack class extends Vector to add methods for a simple last-in first first-out stack of Object

(1) Mehods

• public boolean empty()• public Object peek()• public Object pop()• public Object push(Object item) • public int search(Object item)

(2) Example

Using Stack to keep track of who currently has borrowed something

Stack

Page 14: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-16]Programming in Java

import java.util.Stack public class Borrow{ private String itemName; private Stack hasIt = new Stack(); public Borrow(String name,String owner){ itemName = name; hasIt.push(owner); } // 首先压进主人的名字 public void borrow(String borrower){ hasIt.push(borrower); } public String currentHolder(){ return (String)hasIt.peek(); } public String returnIt(){ String ret=(String)hasIt.pop(); if(hasIt.empty()); // 不小心把主人弹出 hasIt.push(ret); // 将主人名字入栈 return ret; } }

Example

Page 15: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-17]Programming in Java

• The Dictionary abstract class defines a set of abstract methods to store an element indexed by a particular key, and retrieve the element using that key

• public abstract Object put(Object key,Object element)

• public abstract Object get(Object key)

• public abstract Object remove(Object key)

• public abstract int size()

• public abstract boolean isEmpty()

• public abstract Enumeration keys()

• public abstract Enumeration elements()

Dictionary

Page 16: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-18]Programming in Java

• The hashtable is a common key/element pair storage mechanism

• The hashtable class implements the Dictionary interface

• The other efficiency factor of a hashtable is generation of hashcodes from the keys

(1) Constructors

• public Hashtable()/(int initCapacity)/(int initCapacity, float loadFactor): loadFactor:0.0-1.0(0.75)

(2) Methods • public synchronized boolean containsKey(Object key) • public synchronized boolean contains(Object element)• public synchronized void clear() • public synchronized Object clone()

Hashtable

Page 17: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-19]Programming in Java

• Property list is another common key/element pair,

consisting of string names and associated string elements• The Properties class extends Hashtable , implements the

Enumeration interface• If a property list has been properly populated with only

String keys and elements, you can save and restore it

from files or other I/Ostreams

Properties(1)

(1) Fields: protected Properties defaults;

(2) Constructors

• public Properties()

• public Properties(Properties defaults)

Page 18: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-20]Programming in Java

(3) Methods

• public String getProperty(String key)

• public String getProperty(String key,String default)

• private void save(OutputStream out,String header)

• public synchronized void load(InputStream in) throws

IOException

• public Enumeration propertyNames()

• public void list(PrintStream out)

Properties(2)

Page 19: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-21]Programming in Java

Properties prop = new Properties();

prop.put(“Title”, ”put title here”);

prop.put(“Author”, “your name here”);

prop.put(“isbn”, ”isbn not set”);

Properties book = new Properties(prop);

book.put(“Title”, “java ”);

book.put(“Author”, “Li”);

Example

Hashtable ht = new Hashtable();

ht.put(“one”, new Integer(1));

ht.put(“two”,new Integer(2));

ht.put(“three”,new Integer(3));

System.out.println(“TWO: ”+ht.get(“two”))

Page 20: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-22]Programming in Java

• The StringTokenizer class breaks a string into parts,

using delimiters• A sequence of tokens broken out of a string is an ordered

enumeration of those tokens, so StringTokenizer

implements the Enumeration interface

(1) Constructors

• public StringTokenizer(String str, String delim, boolean returnTokens)

• public StringTokenizer(String str,String delim)

Equals: StringTokenizer(str,delim,false)

• public StringTokenizer(String str)

Equals: StringTokenizer(str," \t\n\r")

StringTokenizer(1)

Page 21: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-23]Programming in Java

(2) Methods• public boolean hasMoreTokens() • public String nextToken() • public String nextToken(String delim) • public int countTokens()

(3) Example

• To break a string into tokens separated by spaces and commas

String str = "Gone, and forgotten";

StringTokenizer tokens = new StringTokenizer(str," ,");

while(token.hasMoreTokens())

System.out.println(token.nextToken());

Goneand

forgotten

StringTokenizer(2)

Page 22: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-24]Programming in Java

import java.util.StringTokenizer;

class STDemo {

static String in = “title=java: author=Li:”+

“email=Ln@nju”;

public static void main(String args[]){

StringTokenizer st= new StringTokenizer(in,”= :”);

while (st.hasMoreTokens()) {

String key = st.nextToken();

String value = st.nextToken();

System.out.println(key+”\t”+value); }

}

}

•Analyseing “name=value”

Title java

Author Li

Email ln@nju

Example

Page 23: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-25]Programming in Java

• Different from java.lang.Math.Random //return Double

(1) Constructors

• public Random()

• public Random(long seed)

(2) Methods

• public synchronized void setSeed(long seed)• public int nextInt() • public long nextLong()• public float nextFloat()• public double nextDouble()• public synchronized double nextGaussian()

Random

Page 24: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-26]Programming in Java

Collections in Java2

• Manipulate grouped data as a single object

– Java provides List, Set, Map

– add, contains, remove, size, loop over, sort, …

• Insulate programmer from implementation

– array, linked list, hash table, balanced binary tree

• Can grow as necessary

• Contain only Objects (reference types)

• Heterogeneous

• Can be made thread safe (simultaneous access)

Page 25: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-27]Programming in Java

Iterator Collection Map

ListIterator List Set AbstractMapAbstractCollection

AbstractList AbstractSet

ArraySet HashSet

AbstractSequentialList

ArrayList LinkedList

ArrayMap TreeMap

HashMap Hashtable

Vector

Stack Comparable Comarator

Collections

Array

New Collection

Page 26: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-28]Programming in Java

Example

Import java.util.*;

Public class SimpleCollection {

public static void main(String[] args) {

Collection c = new ArrayList();

for (i = 0; i <10; i++)

c.add(Integer.toString(i));

Iterator it = c.iterator();

while (it.hasNext())

System.out.println(it.next());

}

}

Page 27: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-29]Programming in Java

• Collection constructors (several signatures): new ArrayList() new HashSet( int size ) new LinkedList( Collection c )

• Can choose implementation• Can provide optional size (for performance)

Collection (the common abstraction)

• Methods(some)int size();

boolean add( Object obj );

returns true if Collection changes as a result of the add (it always will for List, may not for Set)

boolean contains( Object obj );

Page 28: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-30]Programming in Java

• Like an array

– elements have positions indexed 0…size( )-1

– duplicate entries possible

• Unlike an array

– can grow as needed

– can contain only Objects (heterogeneous)

– easy to add/delete at any position

– API independent of implementation (ArrayList, Li

nkedList)

List

Page 29: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-31]Programming in Java

Exampleimport java.util.*;

public class ArrayListDemo{

public static void main(String[] args) {

List l = new ArrayList();

l.add("Hello"); l.add("World");

l.add(new Character(' 我 '));

l.add(new Integer(23));

l.add("Hello");

String[] as = {"W","o","r","l","d"};

l.add(as); l.add(new Integer(23));

l.add(23);

System.out.println(l); }

}

//

[Hello, World, 我 , 23, Hello, [Ljava.lang.String;@20c10f, 23]

Page 30: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-32]Programming in Java

• Like a List – can grow as needed

– can contain only Objects (heterogeneous)

– easy to add/delete

– API independent of implementation (HashSet, TreeSet)

• Unlike a List– elements have no positions

– duplicate entries not allowed

Set

Page 31: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-33]Programming in Java

Exampleimport java.util.*;

public class HashSetDemo{

public static void main(String[] args) {

Set s = new HashSet();

s.add("Hello"); s.add("World");

s.add(new Character(' 我 '));

s.add(new Integer(23)); s.add("Hello");

String[] as = {"W","o","r","l","d"};

s.add(as); s.add(null);

s.add(new Integer(23));

s.add(null);

System.out.println(s); }

} [World, 我 , [Ljava.lang.String;@47e553, 23, null, Hello]

Page 32: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-34]Programming in Java

Iterator Interface

// suppose Collection of Programmer objects

Iterator iter = engineers.iterator();

while (iter.hasNext()) {

Programmer p = (Programmer)iter.next();

p.feed("pizza");

}

• Note cast (Programmer) since Collection and Iterator manage anonymous objects

• When collection has a natural ordering, Iterator will respect it

• Supports safe remove() of most recent next

Page 33: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-35]Programming in Java

Exampleimport java.util.*;

public class SetIteratorDemo{

public static void main(String[] args) {

Set s = new HashSet();

s.add("Hello");

s.add("World");

s.add(new Character(' 我 '));

s.add(new Integer(23));

s.add(new Double(23.12));

s.add(null);

Iterator i = s.iterator();

System.out.println("[");

boolean first = true;

Page 34: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-36]Programming in Java

Examplewhile (i.hasNext()) {

System.out.print(i.next() + "");

if (first) {

i.remove();

first = false;} }

System.out.println("]");

i = s.iterator();

System.out.print("[");

while (i.hasNext())

System.out.print(i.next() + "");

System.out.println("]"); }

} [World, 我 , 23.12, 23, null, Hello ]

[ 我 , 23.12, 23, null, Hello ]

Page 35: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-37]Programming in Java

Map

• Table lookup abstraction

– void put( Object key, Object value)

– Object get( Object key)

• can grow as needed any Objects for key and value

(keys tested for equality with .equ

als, of course)

• API syntax independent of implementation (Ha

shMap, TreeMap)

• Iterators for keys, values, (key, value) pairs

Page 36: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-38]Programming in Java

Example

import java.util.*;

import java.io.*;

public class HashMapDemo{

public static void main(String[] args) {

HashMap hm = new HashMap();

hm.put("1",new Integer(1));

hm.put(new File("test.txt"), "2");

hm.put(new Byte((byte)3),System.out);

hm.put(null, "nothing");

Set s = hm.keySet();

Iterator i = s.iterator();

Page 37: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-39]Programming in Java

Example

while (i.hasNext()) {

Object k = i.next();

Object v = hm.get(k);

System.out.print(""+k+"="+v);

if (v instanceof PrintStream)

((PrintStream)v).print("(IT'S ME!)");

}

}

l=1, 3=java.io.PrintStream@310d42(IT’S ME), null=nothing test.txt=2

Page 38: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-40]Programming in Java

Computing FactorialComputing Factorial

• The factorial of an integer is the product of that number and all of the positive integers smaller than it.- 5! = 5*4*3*2*1 = 120- 50! =

30414093201713378043612608166064768844377641568960512000000000000

Page 39: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-41]Programming in Java

Computing Computing Factorials(1)Factorials(1)

public class Factorial {public static int factorial(int x) {

int fact = 1;for (int i =2; i <= x; i ++) //loop

fact *= i; //shorthand for: fact=fact*i;

return fact;}

}public class ComputingFactorial {

public static void main(String arg[]) { int a = Factorial.factorial(Integer.parseInt(arg[0]

)); System.out.println(a); }

}

• A simple class to compute factorials:

Page 40: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-42]Programming in Java

public class Factorial2 {//create an array to cache values 0! Through 20!Static long[] table = new long[21];Static {table[0] = 1;} //factorial of 0 is 1//Remember the highest initialized value in the array

static int last = 0; public static long factorial(int x) {

while (last < x) { table [last + 1] = table[last]*(last + 1); last++;

}}

Computing Computing Factorials(2)Factorials(2)

• Caching factorials

Page 41: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-43]Programming in Java

• Recursive Factorials

/*** This class shows a recursive method to compute factorials. This method* calls itself repeatedly based on the formula: n! = n*(n-1)!**/public class Factorial3 {

public long factorial(int n) {if (n == 1) return n; // 递归头else return n*factorial(n - 1); // 递归调用自己

}}

Computing Computing Factorials(3)Factorials(3)

Page 42: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-44]Programming in Java

• fibonacci(n) = n, n=0,1; fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) , n 为其它整数

public long fibonacci(int n) {if (n == 0 || n == 1 )

return n;else

return (fibonacci(n - 1)*factorial(n - 2));}

FibonacciFibonacci

Page 43: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-45]Programming in Java

Sorting Sorting NumbersNumbers

• Sorting:Input n numbers, sort them such that the numbers are ordered increasingly.

3 9 1 6 5 4 8 2 10 7

1 2 3 4 5 6 7 8 9 10

•Sorting algorithm

Page 44: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-46]Programming in Java

Bubble Sorting(1)Bubble Sorting(1)

• A simple sorting algorithm

main idea: Algorithm

Input: an array A containing n integers.

Output: sorted array.

1. i := 2;

2. Find the least element a from A(i) to A(n);

3. If a is larger than A(i - 1), exchange A(i - 1) and a;

4. i := i + 1; goto step (2).

Page 45: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-47]Programming in Java

• A simple sorting

1st step: 3 9 1 6 5 4 8 2 10 7

2nd step: 3 1 6 5 4 8 2 9 7 10

1 3 2 4 5 6 7 8 9 10 … ... 1 2 3 4 5 6 7 8 9 10

swap

swap

Bubble Sorting(2)Bubble Sorting(2)

swap

Page 46: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-48]Programming in Java

void SortProcedure() { int pass,i,temp,exchangeCnt; for (pass = 0; pass<DataArray.length; pass++) {// 扫描多次 exchangeCnt = 0; for (i =0; i< DataArray.length-pass-1; i++ ) {// 一次扫描过程 if (DataArrary[i] > DataArrary[i+1] ) {// 一次两两交换过

程 temp = DataArray[i]; DataArray[i] = DataArrary[i+1] ; DataArrary[i+1] = temp; exchangeCnt++; } } for (i =0; i< DataArray.length; i++ ) SortPro[pass+1][i] = DataArray[i];// 记录本轮扫描后数据 if (exchangeCnt ==0) return; // 排列情况 } }

Bubble Sorting(3)Bubble Sorting(3)

Page 47: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-49]Programming in Java

…int[] DataArray = new int[10]; // 待排序数据的数组int[] [] SortPro = new int[11][10]; // 保存排序过程的二维数组

Bubble Sorting(4)Bubble Sorting(4)

if (e.getSource() = = sortbn)

{

for (i =0; i< DataArray.length; i++ ) // 记录未排序的原始数据 SortPro[0][i] = DataArray[i];SortProcedure(); // 调用排序方法repaint();

}…

Page 48: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-50]Programming in Java

• Select sortingmain idea: Algorithm

Input: an array A containing n integers. It split

two parts, one is sorted(initialization=null),the other is

unsorted(initialization=full of sorting integers)

Output: sorted array.

1. i := 0;

2. Find the least element a from A(i) to A(n);

3. Put a in sorted part;(unsorted part reduce a

)

4. i := i + 1; goto step (2).

Select Sorting(1)Select Sorting(1)

Page 49: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-51]Programming in Java

• Select sorting

1st step: 3 9 1 6 5 4 8 2 10 7

2nd step: 1 9 3 6 5 4 8 2 10 7

… ...

1 2 3 4 5 6 7 8 9 10

Select Sorting(2)Select Sorting(2)

Page 50: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-52]Programming in Java

void SortProcedure() { int pass,i,temp,k; for (pass = 0; pass<DataArray.length; pass++) {// 选择多次,

有序子列在增长 for (i =pass; k=i; i< DataArray.length; i++ )// 一次选择 if (DataArrary[i] < DataArrary[k] ) // 未排序中最小者 k = i; temp = DataArray[pass]; // 排在剩余数据的最前面 DataArray[pass] = DataArrary[k] ; DataArrary[k] = temp; for (i =0; i< DataArray.length; i++ ) SortPro[pass+1][i] = DataArray[i];// 记录本轮选择后数据

排列情况 }}

Select Sorting(3)Select Sorting(3)

Page 51: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-53]Programming in Java

Insert Sorting(1)Insert Sorting(1)

• Inset sortingmain idea: Algorithm

Input: an array A containing n integers. It split

two parts, one is sorted(initialization=null),the other is

unsorted(initialization=full of sorting integers)

Output: sorted array.

1. i := 0;

2. Find the least element a from A(i) to A(n);

3. Put a in the appropriate location in the sort

ed

part

4. i := i + 1; goto step (2).

Page 52: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-54]Programming in Java

• Insert sortmain idea:

1st step: 3 9 1 6 5 4 8 2 10 7

2nd step: 3 9 1 6 5 4 8 2 10 7

3rd step: 1 3 9 6 5 4 8 2 10 7

… ...

1 2 3 4 5 6 7 8 9 10

Insert Sorting(2)Insert Sorting(2)

Page 53: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-55]Programming in Java

void SortProcedure() { int pass,i,temp; for (pass = 1; pass<DataArray.length; pass++) { // 插入多次 temp = DataArray[pass]; // 本次插入到有序子列中的数据 for (i =pass-1; i>=0; i-- ) // 一次插入过程,有序子列在增长 if (DataArrary[i] < =temp ) // 选择有序子列中的合适位置 break; else DataArray[i+1] = DataArrary[i] ;// 腾出空位置 DataArrary[i+1] = temp; //i+1 是合适的位置,插入新数据 for (i =0; i< DataArray.length; i++ ) SortPro[pass][i] = DataArray[i];// 本轮排序后数据排列情

况 }}

Insert Sorting(3)Insert Sorting(3)

Page 54: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-56]Programming in Java

Data Structures in Memory

• Data is stored in contiguous memory (arrays) or in a linked structure (linked lists, trees) Array

Linked Structure

2 8 9 11 14 14 22 24 27 31

Page 55: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-57]Programming in Java

Trees Are also Implemented as Linked Structures

50

7525

12 35

28 41

66 90

81 95

91 100

54

Page 56: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-58]Programming in Java

Linked Structure

• Now use a linked structure rather than an array• A "linked" structure has elements that also

contains a reference to another objectThe beginning of the list is referenced by firstThe last element has a reference to nothing: null

Page 57: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-59]Programming in Java

Why study linked structures?

• Linked structures use memory more efficiently The size of a linked structure (number of elements)

can grow and shrink at runtime

Arrays may have thousands of unused elements

• This is not too dramatic in Java. Arrays store

references which are only 4 bytes (32 bits) of

memory

• In other languages, each array element may take

up hundreds of bytes of memory

• Linked structures are used to implement trees an important data structure to be discussed later

Page 58: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-60]Programming in Java

Storing Many Objects

• We have examined 2 major ways to store data in the main memory of the computerarrays

– use subscripts to immediately access elements

– fast access, but in the old days would consume more memory that you would like it to (not true anymore)

linked structures

– each node refers to the next in the collection. To get one to you often traverse sequentially

– slower, but in the old days, managed memory better

Page 59: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-61]Programming in Java

Using Arrays to Store Data

• Bad: 997 reference variables not used: Object[] my_data = new Object[1000];

int n 3

my_data[0] "First";

my_data[1] 123;

my_data[2] 45.6789; unused null unused null

• Good: you can directly access elements without the overhead of method calls my_data[2] // get it immediately

Page 60: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-62]Programming in Java

• Use only as many nodes as you wish ListNode first = new ListNode( "First" ); first.next = new ListNode( "second" ); first.next.next = new ListNode( "third" );

Using Linked Structures

• But you have overhead of an extra reference (next) and you must traverse the linked nodes sequentially

Page 61: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-63]Programming in Java

Slow Insertions

• Consider inserting into an ordered arraySort after each insert? Very slow: n2 comparisons

Find location and move all to the next index to make room for the new one, faster, n comparisons

• Consider inserting into a linked listfaster but still requires n comparisons

• Wouldn't it be nice to insert in less timeCan be done with a tree that requires log2n

comparisons when n = 1024, make 10 comparisons

Page 62: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-64]Programming in Java

A Linked List

• A linked list• Stores a collection of objects in a sequential fashion

– Start at the beginning to find anything

• Is a collection of nodes where each node stores

– a reference to the data

– a reference to another node via a special instance variable called the link field

• Maintains just enough memory when needed

– However, the risk is slower searches, which are performed sequentially

Page 63: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-65]Programming in Java

Node of LinkList

Class Node {

private int m_Data; // 保存数据

Private Node m_Next; // 指向下一个 Node 对象的对象引用

Node(int data) {

m_Data = data; m_Next = null; }

Node (int data, Node next) {

m_Data = data; m_Next = next; }

void setData(int data) { m_Data = data; }

int getData() {return m_Data;}

void setNext(Node next) { m_Next = next; } // 修改指针

Node getNext() { return m_Next; } // 获得指向的对象引用

}

Page 64: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-66]Programming in Java

LinkList-Traverseclass LinkList { Node m_FirstNode; LinkList() { m_FirstNode = null; } LinkList(int data) { m_FirstNode = new Node(data); } String visitAllNode() { // 遍历表的每一个节点,串成一个字符串 Node next = m_FirstNode; String s = “”; while (next != null) { s = s+next.getData() + “;”; next = next.getNext(); } return s; } void insertAtBegin(int data) { // 在链表前面插入节点 if (m_FirstNode == null) m_FirstNode = new Node(data);// 若空则直接插入 else // 插在第一个节点前面 m_FirstNode = new Node(data, m_FirstNode); }

Page 65: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-67]Programming in Java

LinkList-Insert

Void insertAfterId(int data, int id) {// 在某个节点后插入数据

Node next = m_FirstNode;

if (next == null)

m_FirstNode = new Node(data);

else {

while (next.getNext() != null && next.getData() != id)

next = next.getNext(); //next 指向下一个节点

next.setNext(new Node(data, next.getNext());

}

}

Page 66: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-68]Programming in Java

Queues: FIFO

• A Queue is another name for waiting line• Ex: Submit jobs to a network printer• Queue have First In First Out (FIFO) access t

o elements

Page 67: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-69]Programming in Java

Is There a Java Queue Class?

• Some languages have a queue class or Queue is pa

rt of a library that works with the language

Java does not

it uses class Linked List to offer the functionalit

y

• Outline of what we'll do

discuss methods of a Queue

show it’s implementation with a linked struct

ure

Page 68: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-70]Programming in Java

Designing a Queue Methods

• Queues typically provide these operations enqueue adds an element at the end of the queue

getFront returns a reference to the element at the fro

nt of the queue

dequeue removes the element from the front of the qu

eue

isEmpty returns false if there is at least one element i

n the queue

• So we will accept these methods for queue by LinkList

Page 69: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-71]Programming in Java

Queue

class Queue extends LinkList {

boolean isEmpty() { // 判断队列是否为空

if (m_FirstNode == null) reurn true;

else return false;}

void enqueue(int newdata) { // 在队尾加一个数据

Node next = m_FirstNode;

if (next == null) m_FirstNode = new Node(newdata);

else { while (next.getNext() != null)

next = next.getNext();

next.setNext(new Node(newdata));} }

int dequeue() {…

} // 从队头取数据

Page 70: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-72]Programming in Java

UseQueue

Public class UseQueue {

public static void main(String[] args) {

Queue queue = new Queue();

for (int i =0; i<8; i++ ) {

queue.enqueue(i);

System.out.println(queue.visitAllNode()); }

while (!queue.isEmpty()) {

System.out.print(queue.dequeue()+” 出队;” ) ; System.out.println(” 队中还有:” + queue.visitAllNo

de()) ; }

}

}

Page 71: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-73]Programming in Java

Another Linked Structure

• We now turn our attention to a third major way of storing data: the TreeOne implementation of a binary tree has nodes with a

left and right link field

1

32

root

edges

nodes

Page 72: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-74]Programming in Java

Binary Trees

• N-ary tree has n children max from each node• A binary tree is a tree where all nodes have zero, one

or two children no more than 2• Each node is a leaf, has a right child, has a left child,

or has both a left and right child

A

CB

FD E

Page 73: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-75]Programming in Java

Binary Tree Defined

• A binary tree is either: an empty tree consists of a node, called a root, and zero, one, or two

children (left and right ), each of which are themselves binary trees

• This recursive definition uses the term "empty tree" as the base case

• Every non-empty node has two children, either of which may be empty On previous slide, C's left child is an empty tree.

Page 74: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-76]Programming in Java

Binary Trees

• Binary trees are used to implement other data structures such asBinary search trees

• logarithmic (faster than linked lists) access and insertion

Priority queues• support access to the minimum

• print queues that retrieve the shortest print job rather than the a long print job that was requested in a FIFO order

Page 75: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-77]Programming in Java

Class Search Binary TreeNode

• Each BinaryTreeNode object has the data object so we can store anything

a link to the left subtree which could be an empty tree

a link to the right subtree which could be an empty tree

• The data fields are private But an enclosing class has access to the private inner cl

ass instance variables

• no other class has access

49

7815

3 37

21 46

Page 76: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-78]Programming in Java

Class Search Binary TreeNode(1)

class TreeNode {

TreeNode m_LeftPoint;

TreeNode m_RightPoint;

private int m_Data;

TreeNode(int newdata) {

m_Data = newdata; m_LeftPoint = null;

m_RightPoint = null; }

int getData() { return m_Data;}

void setData(int newdata) {m_Data = newdata;}

TreeNode getLeftPoint() {return m_LeftPoint;}

TreeNode getRightPoint() {return m_RightPoint;}

Page 77: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-79]Programming in Java

Class Search Binary TreeNode(2)

void insertNode(int newdata) { // 递归插入新节点

if (newdata >= getData()) {

if (m_RightPoint == null)

m_RightPoint = new TreeNode(newdata); // 递归头

else

m_RightPoint.insertNode(newdata); // 递归调用 }

else

if (m_LeftPoint == null)

m_LeftPoint = new TreeNode(newdata); // 递归头

else

m_LeftPoint.insertNode(newdata); // 递归调用 }

}

Page 78: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-80]Programming in Java

Recursion and Trees

• Trees are defined recursively and tree algorithms are implemented recursively

• For example, size (all descendants plus 1) // call a size after building a tree

System.out.println( size( root ) );

public static int size( BinaryTreeNode t ) { // return size of tree rooted at t if( t == null ) return 0; else return 1 + size(t.left) + size(t.right); }

Page 79: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-81]Programming in Java

Some Tree Traversals (PreOrder First)

• The process of visiting each element in a list is called a list traversal. There are 3 tree traversals.

• The Preorder traversal says, visit the root of each tree, then proceed left.

• Recursion then backs us up to visit the right.

• Here’s the algorithmif the tree is not empty

visit the root

preOrderTraverse(left Child)

preOrderTraverse (right Child)

Page 80: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-82]Programming in Java

Build a Tree with Search Binary TreeNodeclass BinaryTree {

TreeNode m_RootNode; // 根节点 BinaryTree (int rootdata) {

m_RootNode = new TreeNode(rootdata); }

void insertToTree(int newdata) // 插入一个新数据 {m_RootNode.insertNode(newdata);}

String preOrderReview() { // 先遍历整棵树 return preOderReview(m_RootNode); }

String preOrderReview(TreeNode subRoot) { // 先遍历 subRoot 子树 String s = “”;

if (subRoot == null) return s; // 递归头 else { s= s+subRoot.getData+”;”; // 先访问当前根节点 s= s+preOderReview(subRoot.getLeftPoint()); // 访问左子树 s=s+ preOderReview(subRoot.getRightPoint()); // 访问右子树 return s; } …

Page 81: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-83]Programming in Java

Traverse The Binary Tree with Circulation

String searchData(int ky) { // 用循环查找二叉树

String s = “”;

TreeNode next = m_RootNode;

while (next != null) { // 直到叶节点

s=s+next.getData()+”;”; // 记录查找过程中的比较

if (next.getData() == key)

return s+” 找到”; else if (key > next.getData()) // 到右子数查找

next = next.getRightPoint();

else

next = next.getLeftPoint(); }

return s+” 未找到”; }

Page 82: [8-1] Programming in Java Java Tool Packages (2) Lecture8

[8-84]Programming in Java

Assignment

1 、 P932 19.10

2 、 P992 20.19

3 、用桶排序方法对“ 0 、 31 、 81 、 1 、252 、 142 、 45 、 297 、 7 、 18”排序,并输出排序过程和结果

4 、编写用链表实现的一个搜索二叉树,并输出给定数据“ 49 、 45 、 80 、 11 、18 、 106 、 55 、 251 、 91” 的先序、中序和后序的排列结果,并查找用户输入的数据并输出结果(要求用递归实现遍历)