如何分辨Java中变量和参考之间的区别?
我来自C和C ++的背景,在那里我对指针和参考文献感到非常满意。现在,我正在Java中学习数据结构和算法,我看到一个幻灯片在谈论链接列表中的节点是构造的,
class Node<E>{
E element;
Node<E> next;
public Node(E o){
element = o;
}
}
因为我的背景是我的背景,这看起来像是直接包含在该节点中的下一个节点,而且没有什么可是阐明这是对内存中单独地址的参考(指针?)。我也知道这一点,Java根本没有通过传递引用,这使得这个甚至更奇怪(从我的角度来看)。因此,我想知道,我如何判断容纳实际值或对象的变量之间的区别,以及对其他值/对象的引用的变量
I'm coming from a background in C and C++, where I grew pretty comfortable with pointers and references. Now I'm learning Data Structures and Algorithms in Java, and I saw a slide talking about nodes in Linked Lists being structured as so
class Node<E>{
E element;
Node<E> next;
public Node(E o){
element = o;
}
}
Given my background, to me this looks like the next node is contained directly within this node, and there's nothing to clarify that it's a reference (pointer?) to a separate address in memory. I also know at this point that Java doesn't have pass-by-reference at all, which makes this even weirder (from my perspective). So I want to know, how do I tell the difference between variables that hold actual values or objects, and variables that hold references to other values/objects
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在Java中,与C或C ++不同,所有具有原始类型类型的变量都是参考。在这种情况下,
Next
是参考,因为节点
是对象,而不是原始的对象。元素
也将是对另一个对象的引用,除非e
是原始对象。 Java的垃圾收集器处理这些引用的所有内存管理,因此您无需担心分配和释放基础对象的内存。例如:In Java, unlike C or C++, all variables with types that are not primitives are references. In this case,
next
is a reference becauseNode
is an object, not a primitive.element
would also be a reference to another object, unlessE
is a primitive. Java's garbage collector handles all the memory management for these references, so you don't need to worry about allocation and freeing the memory for the underlying objects. For example:在Java中,变量分为两类。
int,Short,Boolean,char,long,byte,double,float
),类型参数
e
在此上下文中不能是原始类型,因此在您的代码中,element
andnext
都存储了对某物的引用。这就是为什么您的班级成功实现链接列表的原因。至于如何与“通过值” - 参数值传递给方法的问题是原始或参考值,就像其他任何Java变量的值一样。因此,如果您的参数是参考类型,而不是原始参数;然后,尽管您正在做“按价值传递”,但它的行为有点像“通过参考”,而现在所调用的方法可以访问原始对象,而不是副本。当然,这并不是真正的“通过参考”,因为所谓的方法无法更改原始变量所指的内容。
In Java, variables fall into two categories.
int, short, boolean, char, long, byte, double, float
),The type parameter
E
can't be a primitive type in this context, so in your code,element
andnext
both store references to something. That's why your class succeeds in implementing a linked list.As for the question of how this works with "pass by value" - argument values passed to a method are either primitives or references, just like the values of any other Java variable. So if your parameter is a reference type, not a primitive; then although you're doing "pass by value", it behaves a little like "pass by reference", insofar as the method being called now has access to the original object, not a copy. Of course, it's not really "pass by reference" because the method that was called can't change what the original variable refers to.