如何将 String 转换为泛型 <E>?

How to convert a String to a generic type <E>?

我有一个二叉树 BinaryTree<E> 具有以下变量

protected E data;
protected BinaryTree<E> left,right;

教授给我的,并要求我使用以下代码(此处仅显示相关代码)成功完成的每个节点的值加倍:

if (data != null) {
  this.setData(String.valueOf(Integer.parseInt(getData().toString()) * 2));
}

不幸的是,这会引发以下警告,我想将其删除:

1 error found:
Error: incompatible types: java.lang.String cannot be converted to E

有什么想法吗?

你的 BinaryTree 是泛型类型,所以每次当你使用 this.setData(...) 它会期望您在其中设置的任何类型都是 E 类型。

所以你的代码可以工作,你必须添加 E 数据类型。

所以,你有两个解决方案:

  • 为您的二叉树删除 E class,您的数据 field/methods 将存储 "java.lang.Object" 因此您可以将数据直接设置为字符串或更好地设置为 boxed double (新双(...))

  • 在您使用 BinaryTree class 的地方,例如,对于您的附加值,请使用 BinaryTree 的专用版本,例如:BinaryTree node = new BinaryTreeNode(); node.setData(新双 (3.5));

您将必须以 E 作为参数来实现 setData。如果你实现setData时传入的参数类型是String,那么就会报String不能转E的错误。参考下面的代码:

public class BinaryTree<E> {
    E data;

    BinaryTree<E> left, right;

    public void doubleEachElement() {
        BinaryTree temp = this;
        if (temp != null) {
            if (temp.data != null) {
                temp.setData(String.valueOf(Integer.parseInt(temp.getData().toString()) * 2));
            }
            this.left.doubleEachElement();
            this.right.doubleEachElement();
        }
    }

    // private void setData(String valueOf) {// This would throw an error
    // stating the String cannot be converted to E
    // data = valueOf;
    // }
    public void setData(E valueOf) {
        data = valueOf;
    }

    public E getData() {
        return data;
    }

    public void printBTreeInorder() {
        BinaryTree temp = this;
        if (this != null) {
            System.out.println(data);
        }
        if (this.left != null)
            this.left.printBTreeInorder();
        if (this.right != null)
            this.right.printBTreeInorder();
    }

    public static void main(String[] args) {
        BinaryTree<Integer> intBTree = new BinaryTree<>();
        intBTree.setData(3);
        intBTree.printBTreeInorder();
        intBTree.doubleEachElement();
        intBTree.printBTreeInorder();
    }
}

未注释的注释行会导致您在问题中提到的相同错误。