Lecture 10 1 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 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 Using Libraries 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. Using Libraries package 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); } Using Libraries private 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 label dataset, // data PlotOrientation.VERTICAL, // orientation false, // don't include legend true, // tooltips? false // URLs? ); 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); } } PDFBox PDFBox is a library for extracting text from pdfs Get the "Standalone binary" at https://pdfbox.apache.org/downloads.html As is typical for this type of library, it is not well documented. If the demo below is not enough, check Eclipse's contextsensitive help or look for comments on StackOverflow. 9 PDFBox package 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")); } } 10 Using Libraries • See why it's so important to adhere to conventions for things like method name capitalization? 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 G 55 45 F 100 57 67 107 R M A (A ) (B ) 12 T 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. 13 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; 60 root 55 45 100 57 67 public TreeNode(E o) { element = o; } 107 } 14 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 } 15 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. 16 Inserting an Element to a Binary Tree 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 } 17 Insert 101 into the following tree. 60 ro o t 55 45 100 57 67 107 Trace Inserting 101 into the following tree, cont. Several steps omitted… 18 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); Insert 101 into the following else { // Locate the parent node current = root; while (current != null) if (element value < the value in current.element) { 101 < 107 true parent = current; current = current.left; } else if (element value > the value in current.element) { parent = current; current = current.right; 60 ro o t } 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); tree. p aren t 55 45 100 57 67 107 return true; // Element inserted } S in ce cu rren t.left is n u ll,cu rren t b eco m es n u ll 19 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); Insert 101 else { // Locate the parent node current = root; current is null now 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; ro o t } 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); into the following tree. 60 p aren t 55 45 100 57 67 107 return true; // Element inserted } S in ce cu rren t.left is n u ll,cu rren t b eco m es n u ll 20 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); Insert 101 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; ro o t } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) 101 < 107 true parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); into the following tree. 60 p aren t 55 45 100 57 67 107 return true; // Element inserted } S in ce cu rren t.left is n u ll,cu rren t b eco m es n u ll 21 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); Insert 101 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; ro o t } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) 101 < 107 true parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); into the following tree. 60 p aren t 55 45 100 57 67 return true; // Element inserted } 101 22 107 Trace Inserting 101 into the following tree, cont. if (root == null) root = new TreeNode(element); Insert 101 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; ro o t } else return false; // Duplicate node not inserted // Create the new node and attach it to the parent node if (element < parent.element) 101 < 107 true parent.left = new TreeNode(elemenet); else parent.right = new TreeNode(elemenet); into the following tree. 60 p aren t 55 45 100 57 67 return true; // Element inserted } 101 23 107 Inserting 59 into the Tree 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); 60 root 55 45 100 57 67 107 return true; // Element inserted } 59 24 101 Tree Traversal Tree 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. 25 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. 26 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. 27 The Tree Interface «interface» java.lang.Iterable<E> +iterator(): Iterator<E> Returns an iterator for the elements in this collection. «interface» Tree<E> +search(e: E): boolean Returns true if the specified element is in the tree. +insert(e: E): boolean Returns true if the element is added successfully. +delete(e: E): boolean Returns true if the element is removed from the tree successfully. +inorder(): void Prints the nodes in inorder traversal. +preorder(): void Prints the nodes in preorder traversal. +postorder(): void Prints the nodes in postorder traversal. +getSize(): int Returns the number of elements in the tree. +isEmpty(): boolean Returns true if the tree is empty. +clear(): void Removes all elements from the tree. AbstractTree<E> 28 The Tree interface defines common operations for trees, and the AbstractTree class partially implements Tree. The BinaryTree Class Let’s define the binary tree class, named BinaryTree with A concrete BinaryTree class can be defined to extend AbstractTree. BST «interface» Tree<E> AbstractTree<E> TreeNode<E> #element: E #left: TreeNode<E> #right: TreeNode<E> 1 Link m 0 BST<E extends Comparable<E>> #root: TreeNode<E> The root of the tree. #size: int The number of nodes in the tree. +BST() Creates a default BST. +BST(objects: E[]) Creates a BST from an array of elements. +path(e: E): java.util.List<TreeNode<E>> Returns the path of nodes from the root leading to the node for the specified element. The element may not be in the tree. 29 Example: Using Binary Trees See the code from Liang linked from the course web page 30 Tree After Insertions root Inorder: Adam, Daniel George, Jones, Michael, Peter, Tom G eorge A d am M ich ael D an iel Jon es Postorder: Daniel Adam, Jones, Peter, Tom, Michael, George T om P eter Preorder: George, Adam, Daniel, Michael, Jones, Tom, Peter 31 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 32 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). p aren t p aren t cu rren t m ay b e a left or righ t child of p arent cu rren t Su btree m ay b e a left or righ t sub tree of p aren t cu rren t p oin ts th e n od e to b e d eleted N o left ch ild Su btree S u btree 33 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 root 20 root 10 40 40 16 30 27 16 80 50 30 27 34 80 50 Deleting Elements in a Binary Search Tree Case 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 35 Deleting Elements in a Binary Search Tree Case 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. 36 Deleting Elements in a Binary Search Tree Case 2 diagram p aren t p aren t cu rren t m ay b e a left or righ t child of p arent cu rren t p oin ts th e n od e to b e d eleted cu rren t T h e con ten t of th e cu rren t n od e is rep laced b y con ten t b y th e con tent of th e right-m ost n od e. T h e righ t-m ost n od e is d eleted . cu rren t R ight sub tree R ight sub tree . . . . . . p aren tO fR ightM ost p aren tO fR ightM ost C on tent cop ied to cu rren t an d th e n od e d eleted righ tM ost leftC h ild O fR igh tM ost leftC h ild O fR igh tM ost 37 Deleting Elements in a Binary Search Tree Case 2 example, delete 20 20 root 16 root 10 40 10 40 righ tM ost 16 14 30 27 80 30 50 14 27 All other nodes in the left subtree will be left of this one 38 80 50 Examples D elete th is n od e G eorge A d am D an iel A d am M ichael D an iel Jon es M ichael Jon es T om P eter T om P eter If we promoted Adam to root, we would also have to move Daniel to the right subtree 39 Examples D elete th is n od e A d am D an iel D an iel M ichael Jon es M ichael Jon es T om P eter T om P eter 40 Examples D an iel D elete th is n od e D an iel M ichael Jon es Jon es T om T om P eter P eter 41 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. 42