Pointers in Java

前端 未结 9 1979
梦毁少年i
梦毁少年i 2020-12-05 16:28

C++ supports pointers whereas Java does not. But when many programmers questioned how you can work without pointers, the promoters began saying \"Restricted pointers.” So we

相关标签:
9条回答
  • 2020-12-05 17:08

    Pointers are just a way to make mutible return. They not really importend for effektiv work. It is easier to use and you can understand the code better than with pointers. In the most source code in c, I see the more &/*/-> than other things and you have ever look if you need it.

    0 讨论(0)
  • 2020-12-05 17:09

    The terminology is quite fuzzy here.

    Java supports what it calls "references". References act a lot like pointers in C/C++-like languages. They don't act the same way "references" work in those languages.

    The major differences between a pointer in C and a reference in Java are:

    • You can't do pointer arithmetic in Java (i.e. you can't "add" or "subtract" from a Java reference, you can only dereferencere it or compare it with another one).
    • You can't cast it to an incompatible type: Java is strongly type-safe, you can't "re-interpret" the bytes in memory as some other object.

    For some uses of pointers this has no real effect (for example linked lists work pretty much the same in both languages), for others the difference is quite major (arrays in C are just fancy pointer arithmetic, in Java they work quite differently).

    So in a way Java references could be called "restricted pointers".

    Wikipedia defines a pointer as

    ... a programming language data type whose value refers directly to (or "points to") another value

    Emphasis mine. According to this strict definition, Java doesn't have pointers.

    The more general reference is the superclass of pointers, but also contrains more abstract things like file handles or even URLs.

    0 讨论(0)
  • 2020-12-05 17:10

    Java actually does have pointer math. It comes with sun.misc.Unsafe. However, you have to manage the memory yourself - be careful.

    0 讨论(0)
提交回复
热议问题