【问题标题】:Is the reference of JAVA different from the reference of C and C ++?JAVA的引用和C、C++的引用有区别吗?
【发布时间】:2019-01-31 05:27:29
【问题描述】:

我一直在练习和学习 C 和 C++ 中的数据结构。现在我经常使用JAVA语言,一直在用JAVA练习数据结构。

然后出现了一个问题。在创建树的练习中,我做了类似 C 和 C++ 的 Coding,但没有添加 Node。

private Node<E> root;

public void insert(E item) {

    Node<E> r = root;
    insert(r, item);
}

private void insert(Node<E> node, E item) {

    if (node == null) {

        System.out.println(item);
        Node<E> newNode = new Node<>(null, item, null);
        node = newNode;
        return;
    }

    if (node.item.compareTo(item) == -1)
        insert(node.prev, item);
    else
        insert(node.next, item);
}

二进制搜索树。

编码如上完成,没有任何生成。

顺便说一句,

    private Node<E> root;

public void insert(E item) {

    if (root == null) {

        Node<E> newNode = new Node<>(null, item, null);
        root = newNode;
        return;
    }
    Node<E> r = root;
    insert(r, item);
}

private void insert(Node<E> node, E item) {

    if (node.item.compareTo(item) == -1) {

        if(node.prev == null) {

            Node<E> newNode = new Node<>(null, item, null);
            node.prev = newNode;
        }
        else
            insert(node.prev, item);
    }
    else {

        if(node.next == null) {

            Node<E> newNode = new Node<>(null, item, null);
            node.next = newNode;
        }
        else
            insert(node.next, item);
    }
}

树是因为上面的编码而创建的。

总之,

C 或 C++ 中的引用与 JAVA 中的引用不同吗? (这是一个愚蠢的问题,但如果您能解释上述两者之间的区别,我将不胜感激。)

感谢您的回复。

【问题讨论】:

  • C 没有引用。 Java 和 C++ 是非常不同的语言。假设答案是肯定的(Java 和 C++ 中的引用不同)。至少这样你不会失望。如果你很幸运,你可能会感到惊喜;然而,现实世界中很少有这样的结果。
  • 在第一个代码中,root 永远不会被修改,只会被读取。因此,树没有构建。您需要在某处使用“root = ...”行,否则不会发生任何事情。您不能引用引用,而只能引用对象。无论如何,你也不能在 C++ 中做到这一点。所以问题是,您希望发生什么?“等效”但可以工作的 C++ 代码会是什么样子?

标签: java c pointers data-structures binary-search-tree


【解决方案1】:

在java中,函数中的对象参数不像c中的引用,而更像是指针,它是按值传递的,在c中的“.” java 中的运算符的作用类似于 c 中的“->”运算符。

所以如果给参数节点赋值,就如同给c中的指针节点赋值一个新地址,指针是按值传递的。 但是,如果您通过“。”更改其参数来更改对象本身。操作符,就像在c中使用“->”操作符来改变它的参数一样。

【讨论】:

    猜你喜欢
    • 2010-10-01
    • 2017-05-22
    • 2010-09-30
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 2016-08-31
    • 2017-01-25
    相关资源
    最近更新 更多