java参考,Java中的参考究竟是什么?

本文探讨了Java中的引用概念,它并非内存地址,而是类似于C++中的强类型引用。主要区别包括:不能进行指针算术和类型转换。同时,通过对比Java引用与C++指针,指出C++中另有不同类型的引用。深入理解两者在比较o1==o2时的相似性和差异。
摘要由CSDN通过智能技术生成

What exactly is a reference in Java? Is it a memory address? Is a Java reference the equivalent of a dereferenced C++ pointer?

In other words, given the following:

Object o1 = new Object();

Object o2 = new Object();

o1 == o2

Is the above comparison the equivalent of comparing two pointers in C++?

解决方案

o1 == o2 is pretty much equivalent to comparing two pointers in C/C++, yes.

But there are a two main differences between references in Java and pointers in C/C++ that are quite important:

Java references can't do pointer arithmetic: you can't "add 3" to a reference, you can only let it point to another (known) object

Java references are stongly typed: you can't "reinterpret" what lies on the other end of a reference unless you reinterpret it as a type that that object actually is.

Also a short note about the word "reference": C++ has references that act quite differently from both pointers in C and references in Java (but I don't know enough about C++ to tell you the specifics).

For a thorough discussion of this, see this related question on programmers.SE.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值