tailieunhanh - Ivor Horton’s Beginning Java 2, JDK 5 Edition phần 5

so sánh đối tượng. Làm kiểu đối tượng thực hiện một giao diện mà tuyên bố một phương pháp so sánh đối tượng là cách để làm điều này. Một cây nhị phân thực hiện cũng cung cấp một ví dụ về một tình huống mà bạn có thể áp dụng sức mạnh của đệ quy để có hiệu lực rất tốt. | Generic Class Types comparing objects. Making the object type implement an interface that declares a method that compares objects is the way to do this. A binary tree implementation also provides an example of a situation where you can apply the power of recursion to very good effect. Defining the Generic Type You can come to some general conclusions about what the characteristics of your BinaryTree class are going to be by considering how it will work. Objects of type Node are going to be a fundamental part of a binary tree. The Node objects in the tree are really part of the inner workings of the container so they don t need to be known about or accessible externally. It is therefore appropriate if you define Node objects by a private inner class to the BinaryTree class. All nodes in a binary tree must be different but you can allow duplicate data items to be added to a tree by providing for a count of the number of identical objects to be recorded in a Node object. Obviously as a minimum a BinaryTree object will have to store the Node object that is the root node for the tree and provide a method for adding new nodes. It ll also need a method for returning all the data that was stored in the tree in sequence so you need some facility for packaging this. The generic LinkedList type from the previous example provides a convenient facility for this. The type for objects that can be added to the tree must have a method for comparing them. The Comparable interface that is defined in the package declares a single method the compareTo method that will fit the bill. The compareTo method returns a negative integer if the object for which it is called is less than the argument to the method 0 if it equals the argument and a positive integer if it is greater so it does precisely what you need for placing new values in a BinaryTree class object. If you specify the Comparable interface as a constraint on the type parameter for the BinaryTree class it ensures that .