Я пытаюсь написать метод для построения двоичного дерева поиска из заданного ArrayList, который может содержать любой тип сопоставимого объекта T, используя:
@SuppressWarnings("unchecked")
public boolean buildFromList(ArrayList<T> list) {
if (this != null) {
root = null;
}
for (T toInsert : list) {
if (this.find(toInsert) == true) {
return false;
}
this.insert(toInsert);
}
return true;
}
, но когда я пытаюсь передать его, ArrayList, я получаю сообщение об ошибке, утверждающее, что «не может сделать статическую c ссылку на нестатический c тип T», даже если он должен принимать любой объект, реализующий Comparable, который должен быть Integer, поэтому чего мне не хватает ? Код, который я использую для создания ArrayList для его передачи:
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(3);
a.add(2);
a.add(4);
a.add(-1);
System.out.println(buildFromList(a));
Полный код:
import java.util.ArrayList;
/**
* Binary Search Tree Class
*
* The head class for a binary search tree implementation.
*
* @author YOURID
* @param <Comparable> Type of data to store in the binary tree
*/
public class BinarySearchTree<T extends Comparable<T>> {
/**
* A reference pointer to the root of the tree
*/
private BinaryTreeNode<T> root;
private StringBuilder sb = new StringBuilder("");
/**
* Default constructor
*
* Creates a binary tree object with null root note (empty tree)
*/
public BinarySearchTree() {
this(null);
}
/**
* Constructor
*
* Creates a binary tree object with the given node as root
*
* @param newRoot The root of the tree
*/
public BinarySearchTree(BinaryTreeNode<T> newRoot) {
this.root = newRoot;
}
/**
* Get the root of the tree
*
* @return The root of the tree
*/
public BinaryTreeNode<T> getRoot() {
return root;
}
/**
* Set the root of the tree
*
* @param root The new root of this tree
*/
public void setRoot(BinaryTreeNode<T> root) {
this.root = root;
}
/**
* Returns the size of the tree (that is, the
* number of nodes in the tree).
*
*/
public int size() {
if (this.root != null) {
return root.size();
}
return 0;
}
/**
* Returns the height of the tree.
*
*/
public int height() {
if (root != null) {
return root.height();
}
return 0;
}
/**
* Find if an element exists
*
* Checks to see if the value val appears in the
* tree (recursively). Returns true if it appears
* and false otherwise.
*
* @param val The value to find
* @return True if the tree contains the value, false otherwise
*/
public boolean find(T val) {
return findHelper(root, val);
}
private boolean findHelper(BinaryTreeNode<T> current, T value) {
if (current == null) {
return false;
}
if (value.compareTo(current.getData()) == 0) {
return true;
}
return value.compareTo(current.getData()) < 0
? findHelper(current.getLeft(), value)
: findHelper(current.getRight(), value);
}
/**
* Insert an element
*
* Inserts val into the tree where it should appear, returning
* true on success and false otherwise
*
* @param val The value to insert
* @return True on success, false otherwise
*/
@SuppressWarnings("unchecked")
public boolean insert(T val) {
root = insertNode(root, new BinaryTreeNode<T>(val));
return this.find(val);
}
// private recursive call
@SuppressWarnings({ "rawtypes", "unchecked" })
private BinaryTreeNode insertNode(BinaryTreeNode currentParent, BinaryTreeNode newNode) {
if (currentParent == null) {
return newNode;
} else if (newNode.getData().compareTo(currentParent.getData()) > 0) {
currentParent.setRight(insertNode(currentParent.getRight(), newNode));
} else if (newNode.getData().compareTo(currentParent.getData()) < 0) {
currentParent.setLeft(insertNode(currentParent.getLeft(), newNode));
}
return currentParent;
}
/**
* Return a string that represents the data held at each
* node following the rules of an in-order traversal.
*
* Covered in class Wednesday, April 22
*/
public String inOrder() {
sb.setLength(0);
return outputInOrder(root);
}
public String outputInOrder(BinaryTreeNode<T> node) {
if (node != null) {
if (node.getLeft() != null) {
outputInOrder(node.getLeft());
}
sb.append("(" + node.getData() + ")");
if (node.getRight() != null) {
outputInOrder(node.getRight());
}
return sb.toString();
}
return "";
}
/**
* Return a string that represents the data held at each
* node following the rules of a post-order traversal.
*
* Covered in class Wednesday, April 22
*/
public String postOrder() {
sb.setLength(0);
return outputPostOrder(root);
}
public String outputPostOrder(BinaryTreeNode<T> node) {
if (node != null) {
outputPostOrder(node.getLeft());
outputPostOrder(node.getRight());
sb.append("(" + node.getData() + ")");
return sb.toString();
}
return "";
}
/**
* Build from a list
*
* Build the tree from the given list, overwriting any tree data
* previously stored in this tree. Should read from beginning to
* end of the list and repeatedly call insert() to build the tree
*
* If the tree is not empty when this method is called, you should
* empty the tree before adding any elements in list.
*
* @param list The list from which to build the tree
* @return True if successfully built, false otherwise
*/
public boolean buildFromList(ArrayList<T> list) {
if (this != null) {
root = null;
/**root.setLeft(null);
root.setRight(null);*/
}
for (T toInsert : list) {
if (this.find(toInsert) == true) {
return false;
}
this.insert(toInsert);
}
return true;
}
@SuppressWarnings("unchecked")
public boolean buildFromList(ArrayList<T> list) {
if (this != null) {
root = null;
}
for (T toInsert : list) {
if (this.find(toInsert) == true) {
return false;
}
this.insert(toInsert);
}
return true;
}
/**
* toString method
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return inOrder();
}
/**
* Main method
*
* For testing, etc
*
* @param args Command line arguments
*/
public static void main(String[] args) {
BinarySearchTree<Integer> tree = new BinarySearchTree<Integer>();
BinaryTreeNode<Integer> n1 = new BinaryTreeNode<Integer>();
n1.setData(0);
BinaryTreeNode<Integer> n2 = new BinaryTreeNode<Integer>();
n2.setData(1);
BinaryTreeNode<Integer> n3 = new BinaryTreeNode<Integer>();
n3.setData(-1);
BinaryTreeNode<Integer> n4 = new BinaryTreeNode<Integer>();
n4.setData(2);
BinaryTreeNode<Integer> n5 = new BinaryTreeNode<Integer>();
n5.setData(-2);
BinaryTreeNode<Integer> n6 = new BinaryTreeNode<Integer>();
n6.setData(4);
BinaryTreeNode<Integer> n7 = new BinaryTreeNode<Integer>();
n7.setData(-6);
tree.insert(n1.getData());
tree.insert(n2.getData());
tree.insert(n3.getData());
tree.insert(n4.getData());
tree.insert(n5.getData());
tree.insert(n6.getData());
tree.insert(n7.getData());
System.out.println(tree.toString());
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(1);
a.add(3);
a.add(2);
a.add(4);
a.add(-1);
System.out.println(buildFromList(a));
}
}
и я почти полностью уверен в любой другой части код компилируется и работает совершенно нормально