Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Lecture8 Java Tool Packages(2) Programming in Java [8-1] Standard Utilities in Java 1.1 Object Java.lang.Cloneable BitSet Date Vector Dictionary Random StringTokenizer Stack Hashtable Enumeration Observable Properties Observer Programming in Java [8-2] BitSet(1) (1) BitSet class 32 • A BitSet is a set of true and false bits with a size of 2 -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) Programming in Java [8-3] BitSet(2) • 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 Programming in Java [8-4] Enumeration Interface 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 Programming in Java [8-7] Example 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()); Programming in Java [8-8] } Vector • 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 Programming in Java [8-9] Modification Methods • public final synchronized void setElementAt(Object obj, int index) • public final synchronized void removeElementAt(int index) • public final synchronized void insertElementAt(Object obj, int index) • public final synchronized void addElement(Object obj) • public final synchronized boolean removeElement(Object obj) • public final synchronized void removeAllElements() Programming in Java [8-10] Example 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(); } // ..其它方法.... Programming in Java [8-11] Detection Methods 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() Programming in Java [8-12] Capacity Methods • 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)); } Programming in Java [8-13] 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) Programming in Java [8-14] Stack 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 Programming in Java [8-15] Example 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; } } Programming in Java [8-16] Dictionary • 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() Programming in Java [8-17] Hashtable • 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() Programming in Java [8-18] Properties(1) • 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 (1) Fields: protected Properties defaults; (2) Constructors • public Properties() • public Properties(Properties defaults) Programming in Java [8-19] Properties(2) (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) Programming in Java [8-20] 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”)) 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”); Programming in Java [8-21] StringTokenizer(1) • 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") Programming in Java [8-22] StringTokenizer(2) (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," ,"); Gone while(token.hasMoreTokens()) and System.out.println(token.nextToken()); forgotten Programming in Java [8-23] Example •Analyseing “name=value” 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(); Title java System.out.println(key+”\t”+value); } Author Li } Email ln@nju } Programming in Java [8-24] Random • 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() Programming in Java [8-25] 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) Programming in Java [8-26] New Collection Iterator Collection ListIterator List Map Set AbstractMap AbstractCollection AbstractList AbstractSet ArraySet HashSet ArrayMap HashMap AbstractSequentialList ArrayList LinkedList TreeMap Hashtable Collections Array Vector Stack Comparable Programming in Java Comarator [8-27] 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()); } } Programming in Java [8-28] Collection (the common abstraction) • Collection constructors (several signatures): new ArrayList() new HashSet( int size ) new LinkedList( Collection c ) • Can choose implementation • Can provide optional size (for performance) • 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 ); Programming in Java [8-29] List • 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, LinkedList) Programming in Java [8-30] Example import 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] Programming in Java [8-31] Set • 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 Programming in Java [8-32] Example import 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] Programming in Java [8-33] 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 Programming in Java [8-34] Example import 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; Programming in Java [8-35] Example while (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 ] Programming in Java } [8-36] 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 .equals, of course) • API syntax independent of implementation (HashMap, TreeMap) • Iterators for keys, values, (key, value) pairs Programming in Java [8-37] 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(); Programming in Java [8-38] 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 Programming in Java [8-39] Computing 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! = 30414093201713378043612608166064768844377641568960 512000000000000 Programming in Java [8-40] Computing Factorials(1) • A simple class to compute factorials: 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); } } Programming in Java [8-41] Computing Factorials(2) • Caching factorials 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++; } } Programming in Java [8-42] Computing Factorials(3) • 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); //递归调用自己 } } Programming in Java [8-43] Fibonacci • 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)); } Programming in Java [8-44] Sorting Numbers • 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 Programming in Java [8-45] 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). Programming in Java [8-46] Bubble Sorting(2) • A simple sorting 1st step: swap 3 9 1 6 5 4 8 2 10 7 2nd step: swap 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 Programming in Java [8-47] swap Bubble Sorting(3) 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; //排列情况 } } Programming in Java [8-48] Bubble Sorting(4) … int[] DataArray = new int[10]; //待排序数据的数组 int[] [] SortPro = new int[11][10]; //保存排序过程的二维数组 … if (e.getSource() = = sortbn) { for (i =0; i< DataArray.length; i++ ) //记录未排序的原始数据 SortPro[0][i] = DataArray[i]; SortProcedure(); //调用排序方法 repaint(); } … Programming in Java [8-49] Select Sorting(1) • Select sorting main 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). Programming in Java [8-50] Select Sorting(2) • 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 Programming in Java [8-51] Select Sorting(3) 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];//记录本轮选择后数据 排列情况 } } Programming in Java [8-52] Insert Sorting(1) • Inset sorting main 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 sorted part 4. i := i + 1; goto step (2). Programming in Java [8-53] Insert Sorting(2) • Insert sort main 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 Programming in Java [8-54] Insert Sorting(3) 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];//本轮排序后数据排列情况 } } Programming in Java [8-55] Data Structures in Memory • Data is stored in contiguous memory (arrays) or in a linked structure (linked lists, trees) Array 2 8 9 11 14 14 22 24 27 31 Linked Structure "Yean" first "Zorro" "Bob" "Chris" Programming in Java [8-56] Trees Are also Implemented as Linked Structures 50 25 12 75 35 28 66 41 54 90 81 95 91 Programming in Java [8-57] 100 Linked Structure • Now use a linked structure rather than an array • A "linked" structure has elements that also contains a reference to another object The beginning of the list is referenced by first The last element has a reference to nothing: null first "Bob" "Chris" Programming in Java "Yean" [8-58] 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 Programming in Java [8-59] Storing Many Objects • We have examined 2 major ways to store data in the main memory of the computer arrays – 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 Programming in Java [8-60] 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] my_data[2] unused unused 123; 45.6789; null null • Good: you can directly access elements without the overhead of method calls my_data[2] // get it immediately Programming in Java [8-61] Using Linked Structures • Use only as many nodes as you wish ListNode first = new ListNode( "First" ); first.next = new ListNode( "second" ); first.next.next = new ListNode( "third" ); • But you have overhead of an extra reference (next) and you must traverse the linked nodes sequentially first "First" "Second" Programming in Java "Third" [8-62] Slow Insertions • Consider inserting into an ordered array Sort 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 list faster but still requires n comparisons • Wouldn't it be nice to insert in less time Can be done with a tree that requires log2n comparisons when n = 1024, make 10 comparisons Programming in Java [8-63] 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 Programming in Java [8-64] 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; } //获得指向的对象引用 } Programming in Java [8-65] LinkList-Traverse class 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); } Programming in Java [8-66] 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()); } } Programming in Java [8-67] 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 to elements Programming in Java [8-68] Is There a Java Queue Class? • Some languages have a queue class or Queue is part of a library that works with the language Java does not it uses class Linked List to offer the functionality • Outline of what we'll do discuss methods of a Queue show it’s implementation with a linked structure Programming in Java [8-69] 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 front of the queue dequeue removes the element from the front of the queue isEmpty returns false if there is at least one element in the queue • So we will accept these methods for queue by LinkList Programming in Java [8-70] 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() {… } //从队头取数据 Programming in Java [8-71] 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.visitAllNode());} } } Programming in Java [8-72] Another Linked Structure • We now turn our attention to a third major way of storing data: the Tree One implementation of a binary tree has nodes with a left and right link field nodes root 1 2 3 edges Programming in Java [8-73] 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 B D C E Programming in Java F [8-74] 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. Programming in Java [8-75] Binary Trees • Binary trees are used to implement other data structures such as Binary 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 Programming in Java [8-76] 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 class instance variables 49 • no other class has access 15 3 78 37 21 Programming in Java [8-77] 46 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;} Programming in Java [8-78] 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); //递归调用 } } Programming in Java [8-79] } 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); } Programming in Java [8-80] 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 algorithm if the tree is not empty visit the root preOrderTraverse(left Child) preOrderTraverse (right Child) Programming in Java [8-81] Build a Tree with Search Binary TreeNode class 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; } … Programming in Java [8-82] 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+”未找到”;} Programming in Java [8-83] 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”的先序、中序和后 序的排列结果,并查找用户输入的数据 并输出结果(要求用递归实现遍历) Programming in Java [8-84]