不能将ArrayList<Integer>传递给带有arg类型ArrayList<T&gt的方法。

问题描述 投票:0回答:1

我试图写一个方法来从一个给定的ArrayList中构建一个二进制搜索树,这个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传递给它时,我得到了一个错误,说明 "不能对一个非静态类型的T做静态引用",尽管它应该接受任何实现Comparable的对象,而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));

    }
}

我几乎可以肯定其他部分的代码编译和运行都完全正常。

java arraylist comparable
1个回答
-1
投票

你有没有尝试过让T扩展可比较的对象?

喜欢 public boolean buildFromList(ArrayList<T extends Comparable> list) {

© www.soinside.com 2019 - 2024. All rights reserved.