42
Lecture 10 1

Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

Embed Size (px)

Citation preview

Page 1: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

Lecture 10

Page 2: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

Using Libraries• Java has a very strong culture of open-source software• Students, professors, programming hobbyists, and developers who

choose to give back to the profession make many projects available for free

• This allows you to use functionality you lack the time or expertise to code

• It also requires a slightly different set of skills than those you use when you write your own code from scratch. Programming becomes an exercise in hacking other people's ideas so they fit together to get the results you want. You will seldom find that the programmers of the libraries you use thought their work out the same way you would have.

• Quality control is nonexistent and malware is probably sometimes spread this way!

• You will learn several other ways to get libraries and integrate them into your projects, but here is the simple way

Page 3: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

Using Libraries• Find the website for the library you want and download it. • If you have the choice to get the bytecode alone or with the source

included, get the version that includes the source• You will usually need to unzip or untar the library. The free

software 7-Zip can untar, but avoid installing the junkware that comes with 7-Zip.

• The result will include one or more .jar files. Often there is also documentation, tutorials, and other material as well.

• Right click on the project name and choose "Build Path/Configure Build Path", then "Add External JARs", then find the Jar you need to add.

• The library should now appear under "Referenced Libraries" in your project

Page 4: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

Using Libraries

Page 5: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

JFreeChart• JFreeChart is a very widely used free library for creating graphs in

Java.• If the demo below is not enough, google JFreeChart bar graph (or

whatever else you need to look up) for tutorials and discussions, especially on StackOverflow.com

• Download JFreeChart from http://www.jfree.org/jfreechart/download.html

• JFreeChart is not yet easy to use with JavaFX, so the demo below uses Swing

• When you add the JFreeChart jar to the build path for your project, you will also have to add JCommon, which you will get in the download package.

Page 6: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

Using Librariespackage charts;

import java.awt.Color;import java.awt.Dimension;import java.awt.GradientPaint;

import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartPanel;import org.jfree.chart.JFreeChart;import org.jfree.chart.axis.NumberAxis;import org.jfree.chart.plot.CategoryPlot;import org.jfree.chart.plot.PlotOrientation;import org.jfree.chart.renderer.category.BarRenderer;import org.jfree.data.category.CategoryDataset;import org.jfree.data.category.DefaultCategoryDataset;import org.jfree.ui.ApplicationFrame;import org.jfree.ui.RefineryUtilities;

public class BarChartDemo extends ApplicationFrame {

public BarChartDemo(final String title) {super(title);final CategoryDataset dataset = createDataset();final JFreeChart chart = createChart(dataset);final ChartPanel chartPanel = new ChartPanel(chart);chartPanel.setPreferredSize(new Dimension(750, 405));setContentPane(chartPanel);

}

Page 7: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

Using Librariesprivate CategoryDataset createDataset() {

// row keys...final String series1 = "Monster";

// column keys...final String category1 = "Godzilla";final String category2 = "Jersey Devil";final String category3 = "Dracula";final String category4 = "Dick Cheney";

// create the dataset...final DefaultCategoryDataset dataset = new DefaultCategoryDataset();

dataset.addValue(115.5, series1, category1);dataset.addValue(8.5, series1, category2);dataset.addValue(12.0, series1, category3);dataset.addValue(9.0, series1, category4);

return dataset;}

private JFreeChart createChart(final CategoryDataset dataset) {// create the chart...final JFreeChart chart = ChartFactory.createBarChart("Shoe Size Chart", // chart title

"Name", // domain axis label"Shoe Size", // range axis labeldataset, // dataPlotOrientation.VERTICAL, // orientationfalse, // don't include legendtrue, // tooltips?false // URLs?);

Page 8: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

Using Libraries// set the background color for the chart...chart.setBackgroundPaint(Color.white);

// get a reference to the plot for further customisation...final CategoryPlot plot = chart.getCategoryPlot();plot.setBackgroundPaint(Color.lightGray);plot.setDomainGridlinePaint(Color.white);plot.setRangeGridlinePaint(Color.white);

// set the range axis to display integers only...final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

final BarRenderer renderer = (BarRenderer) plot.getRenderer();

// set up gradient paints for series...final GradientPaint gp0 = new GradientPaint(0.0f, 0.0f, Color.blue,

0.0f, 0.0f, Color.lightGray);renderer.setSeriesPaint(0, gp0);

return chart;}

public static void main(final String[] args) {final BarChartDemo demo = new BarChartDemo("Bar Chart Demo");demo.pack();RefineryUtilities.centerFrameOnScreen(demo);demo.setVisible(true);

}}

Page 9: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

9

PDFBox

PDFBox is a library for extracting text from pdfsGet the "Standalone binary" at https://pdfbox.apache.org/downloads.htmlAs is typical for this type of library, it is not well documented. If the demo below is not enough, check Eclipse's context-sensitive help or look for comments on StackOverflow.

Page 10: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

10

PDFBoxpackage pdftograph;

import java.io.File;import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.util.PDFTextStripper;

public class PDFBoxDemo {public void readPDF(File f) {

PDDocument p;PDFTextStripper strip;String text = null;

try {p = PDDocument.load(f);strip = new PDFTextStripper();text = strip.getText(p);} catch (IOException e) {

e.printStackTrace();}System.out.println(text);

}

public static void main(String[] args){PDFBoxDemo reader = new PDFBoxDemo();reader.readPDF(new File("Dracula_T.pdf"));

}}

Page 11: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

Using Libraries

• See why it's so important to adhere to conventions for things like method name capitalization?

Page 12: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

12

Binary Trees

A list, stack, or queue is a linear structure that consists of a sequence of elements. A binary tree is a hierarchical structure. It is either empty or consists of an element, called the root, and two distinct binary trees, called the left subtree and right subtree.

60

55 100

57 67 107 45

G

F R

M T A

(A) (B)

Page 13: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

13

Binary Tree Terms

• The root of left (right) subtree of a node is called a left (right) child of the node. A node without children is called a leaf.

• A special type of binary tree called a binary search tree is often useful. A binary search tree (with no duplicate elements) has this property:– for every node in the tree, the value of any node in its left

subtree is less than the value of the node and the value of any node in its right subtree is greater than the value of the node. Note that this requires a way to order the elements, so in Java we usually either build trees of Comparables or use Comparators

This section is concerned with binary search trees, which, as the name suggests, allow you to easily implement binary search.

Page 14: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

14

Representing Binary Trees

A binary tree can be represented using a set of linked nodes. Each node contains a value and two links named left and right that reference the left child and right child, respectively, as shown in Figure 27.2.

class TreeNode<E> { E element; TreeNode<E> left; TreeNode<E> right;  public TreeNode(E o) { element = o; }}

60

55 100

57 45 67 107

root

Page 15: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

15

Searching an Element in a Binary Tree

public boolean search(E element) { TreeNode<E> current = root; // Start from the root while (current != null) if (element < current.element) { current = current.left; // Go left } else if (element > current.element) { current = current.right; // Go right } else // Element matches current.element return true; // Element is found return false; // Element is not in the tree}

Page 16: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

16

Inserting an Element to a Binary Tree

If a binary tree is empty, create a root node with the new element. Otherwise, locate the parent node for the new element node.

If the new element is less than the parent element, the node for the new element becomes the left child of the parent. If the new element is greater than the parent element, the node for the new element becomes the right child of the parent.

Page 17: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

17

Inserting an Element to a Binary Treeif (root == null) root = new TreeNode(element);else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet);  return true; // Element inserted }

Insert 101 into the following tree.

60

55 100

57 45 67 107

root

Page 18: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

18

Trace Inserting 101 into the following tree, cont.

Several steps omitted…

Page 19: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

19

Trace Inserting 101 into the following tree, cont.if (root == null) root = new TreeNode(element);else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); 

return true; // Element inserted }

Insert 101 into the following tree.

60

55 100

57 45 67 107

root

Since current.left is null,current becomes null

parent

101 < 107 true

Page 20: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

20

Trace Inserting 101 into the following tree, cont.if (root == null) root = new TreeNode(element);else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); 

return true; // Element inserted }

Insert 101 into the following tree.

60

55 100

57 45 67 107

root

Since current.left is null,current becomes null

parent

current is null now

Page 21: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

21

Trace Inserting 101 into the following tree, cont.if (root == null) root = new TreeNode(element);else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); 

return true; // Element inserted }

Insert 101 into the following tree.

60

55 100

57 45 67 107

root

Since current.left is null,current becomes null

parent

101 < 107 true

Page 22: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

22

Trace Inserting 101 into the following tree, cont.if (root == null) root = new TreeNode(element);else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); 

return true; // Element inserted }

Insert 101 into the following tree.

60

55 100

57 45 67 107

root

parent

101

101 < 107 true

Page 23: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

23

Trace Inserting 101 into the following tree, cont.if (root == null) root = new TreeNode(element);else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); 

return true; // Element inserted }

Insert 101 into the following tree.

60

55 100

57 45 67 107

root

parent

101

101 < 107 true

Page 24: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

24

Inserting 59 into the Treeif (root == null) root = new TreeNode(element);else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); 

return true; // Element inserted }

60

55 100

57 45 67 107

root

59 101

Page 25: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

25

Tree TraversalTree traversal is the process of visiting each node in the tree exactly once. There are several ways to traverse a tree. This section presents inorder, preorder, postorder, depth-first, and breadth-first traversals.

Inorder traversal visits the left subtree of the current node first recursively, then the current node itself, and finally the right subtree of the current node recursively.  Postorder traversal visits the left subtree of the current node first, then the right subtree of the current node, and finally the current node itself.

Preorder traversal visits the current node first, then the left subtree of the current node recursively, and finally the right subtree of the current node recursively.

Page 26: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

26

Tree Traversal, cont.Breadth-first traversal visits the nodes level by level. First visit the root, then all children of the root from left to right, then grandchildren of the root from left to right, and so on. For example, in the tree below, the inorder is 45 55 57 59 60 67 100 101 107. The postorder is 45 59 57 55 67 101 107 100 60. The preorder is 60 55 45 57 59 100 67 107 101. The breadth-first traversal is 60 55 100 45 57 67 107 59 101.

Page 27: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

27

Trees

The Java Collections Framework does not contain a general-purpose tree implementation. There is one in Swing that is designed for use with GUI components.

Liang's Introduction To Java Programming contains general-purpose Tree code.

Page 28: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

28

The Tree Interface

The Tree interface defines common operations for trees, and the AbstractTree class partially implements Tree.

«interface» Tree<E>

+search(e: E): boolean

+insert(e: E): boolean

+delete(e: E): boolean

+inorder(): void

+preorder(): void

+postorder(): void

+getSize(): int

+isEmpty(): boolean

+clear(): void

Returns true if the specified element is in the tree.

Returns true if the element is added successfully.

Returns true if the element is removed from the tree successfully.

Prints the nodes in inorder traversal.

Prints the nodes in preorder traversal.

Prints the nodes in postorder traversal.

Returns the number of elements in the tree.

Returns true if the tree is empty.

Removes all elements from the tree.

AbstractTree<E>

«interface» java.lang.Iterable<E>

+iterator(): Iterator<E>

Returns an iterator for the elements in this collection.

Page 29: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

29

The BinaryTree Class

Let’s define the binary tree class, named BinaryTree with A concrete BinaryTree class can be defined to extend AbstractTree.

BST

BST<E extends Comparable<E>>

#root: TreeNode<E>

#size: int

+BST()

+BST(objects: E[])

+path(e: E): java.util.List<TreeNode<E>>

1

m TreeNode<E>

#element: E

#left: TreeNode<E>

#right: TreeNode<E>

Link

0

The root of the tree.

The number of nodes in the tree.

Creates a default BST.

Creates a BST from an array of elements.

Returns the path of nodes from the root leading to the node for the specified element. The element may not be in the tree.

«interface» Tree<E>

AbstractTree<E>

Page 30: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

30

Example: Using Binary Trees

See the code from Liang linked from the course web page

Page 31: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

31

Tree After Insertions

George

Adam Michael

Daniel Jones Tom

root

Peter

Inorder: Adam, Daniel George, Jones, Michael, Peter, Tom

Postorder: Daniel Adam, Jones, Peter, Tom, Michael, George

Preorder: George, Adam, Daniel, Michael, Jones, Tom, Peter

Page 32: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

32

Deleting Elements in a Binary Search Tree To delete an element from a binary tree:• Locate the node that contains the element and also its

parent node. • Let current point to the node that contains the element

in the binary tree and parent point to the parent of the current node.

• The current node may be a left child or a right child of the parent node.

• There are two cases to consider

Page 33: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

33

Deleting Elements in a Binary Search Tree

Case 1: The current node does not have a left child, as shown in this figure (a). Simply connect the parent with the right child, if any, of the current node, as shown in this figure (b).

parent

current

No left child

Subtree

parent

Subtree

current may be a left or right child of parent

Subtree may be a left or right subtree of parent

current points the node to be deleted

Page 34: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

34

Deleting Elements in a Binary Search Tree

For example, to delete node 10 in Figure 27.9a. Connect the parent of node 10 with the right child of node 10, as shown in Figure 27.9b.

20

10 40

30 80

root

50

16

27

20

40

30 80

root

50

16

27

Page 35: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

35

Deleting Elements in a Binary Search TreeCase 2: The current node has a left child.• The left subtree contains some node that contains the

greatest value in the subtree. All the other nodes in the subtree will be left of it in the newly configured tree

• All subtrees of this rightmost value will be to the right of the rightmost node’s parent

Page 36: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

36

Deleting Elements in a Binary Search TreeCase 2: The current node has a left child.• Let rightMost point to the node that contains the largest

element in the left subtree of the current node and parentOfRightMost point to the parent node of the rightMost node, as shown in Figure 27.10a. – Note that the rightMost node cannot have a right child, but may

have a left child.

• Replace the element value in the current node with the one in the rightMost node

• Connect the parentOfRightMost node with the left child of the rightMost node

• Delete the rightMost node, as shown in Figure 27.10b.

Page 37: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

37

Deleting Elements in a Binary Search Tree

Case 2 diagram

parent

current

.

.

.

rightMost

parentOfRightMost

parent

.

.

.

parentOfRightMost

Content copied to current and the node deleted

Right subtree Right subtree

current

current may be a left or right child of parent

current points the node to be deleted

The content of the current node is replaced by content by the content of the right-most node. The right-most node is deleted.

leftChildOfRightMost leftChildOfRightMost

Page 38: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

38

Deleting Elements in a Binary Search Tree

Case 2 example, delete 20

rightMost

20

10 40

30 80

root

50

16

27

16

10 40

30 80

root

50 27 14 14

All other nodes in the left subtree will be left of this one

Page 39: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

39

Examples Delete this

node George

Adam Michael

Daniel Jones Tom

Peter

Daniel

Adam Michael

Jones Tom

Peter

If we promoted Adam to root, we would also have to move Daniel to the right subtree

Page 40: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

40

Examples Daniel

Adam Michael

Jones Tom

Peter

Delete this node

Daniel

Michael

Jones Tom

Peter

Page 41: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

41

Examples Daniel

Michael

Jones Tom

Peter

Delete this node

Daniel

Jones

Tom

Peter

Page 42: Lecture 10 1. Using Libraries Java has a very strong culture of open-source software Students, professors, programming hobbyists, and developers who choose

42

binary tree time complexity

• The time complexity for the inorder, preorder, and postorder is O(n), since each node is traversed only once.

• The time complexity for search, insertion and

deletion is the height of the tree. In the worst case, the height of the tree is n. In the best case it is log n.

• We want our trees to be balanced, so that we get the O(log n) search behavior. That's coming up in the next lecture.