繁体   English   中英

比较Java中可比较的泛型

[英]Comparing Generics that are comparable in Java

我有一个通用二叉树,它将在左边添加小于或等于到的对象,并在右边添加大于的对象。 我的问题是比较泛型,我知道数据值将是对象包装的原语或字符串,因此它们是可比较的。 但是,我不知道如何在代码中实现这一点。

该代码正在开发中,我知道add方法尚未正确添加,但是我正在努力。 谢谢

这是TreeNode:

public class TreeNode<T>
{
    //Instance Variables
    TreeNode leftChild;
    TreeNode rightChild;
    int childCount;
    int depth;
    T data;


    public TreeNode(T data, int parentDepth)
    {
        leftChild = null;
        rightChild = null;
        childCount = 0;
        depth = parentDepth + 1;
        this.data = data;
    }

    public TreeNode(int parentDepth)
    {
        leftChild = null;
        rightChild = null;
        childCount = 0;
        depth = parentDepth + 1;
        data = null;
    }


    public void add(T data)
    {
        if (this.data.compareTo(data) <= 0)
        {
            addLeft(data);
        } else if (this.data.compareTo(data) > 0)
        {
            addRight(data);
        } else
        {
            System.out.println("ERROR IN TREENODE.ADD");
        }
    }


    public void addLeft(T data)
    {
        leftChild = new TreeNode(data, depth);
    }

    public void addLeft()
    {
        leftChild = new TreeNode(depth);
    }


    public void addRight(T data)
    {
        rightChild = new TreeNode(data, depth);
    }

    public void addRight() {
        rightChild = new TreeNode(depth);
    }
}

我知道数据值将是对象包装的原语或字符串,因此它们具有可比性。

然后,您可以告诉编译器:

public class TreeNode<T extends Comparable<T>>

如果你这样做,你会得到访问compareTo中定义的方法Comparable

您的T应该实现Comparable接口以便进行比较。

public class TreeNode<T extends Comparable<T>>
{
    //Instance Variables
    TreeNode leftChild;
    TreeNode rightChild;
    int childCount;
    int depth;
    T data;


    public TreeNode(T data, int parentDepth)
    {
        leftChild = null;
        rightChild = null;
        childCount = 0;
        depth = parentDepth + 1;
        this.data = data;
    }

    public TreeNode(int parentDepth)
    {
        leftChild = null;
        rightChild = null;
        childCount = 0;
        depth = parentDepth + 1;
        data = null;
    }


    public void add(T data)
    {
        if (this.data.compareTo(data) <= 0)
        {
            addLeft(data);
        } else if (this.data.compareTo(data) > 0)
        {
            addRight(data);
        } else
        {
            System.out.println("ERROR IN TREENODE.ADD");
        }
    }


    public void addLeft(T data)
    {
        leftChild = new TreeNode(data, depth);
    }

    public void addLeft()
    {
        leftChild = new TreeNode(depth);
    }


    public void addRight(T data)
    {
        rightChild = new TreeNode(data, depth);
    }

    public void addRight() {
        rightChild = new TreeNode(depth);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM