简体   繁体   English

如何在Java编程语言中添加指针?

[英]How to add pointers in Java programming language?

I am trying to convert the C++ programs into Java programs but I am not able to get the syntax of pointers in java programming language.我正在尝试将 C++ 程序转换为 Java 程序,但我无法获得 Java 编程语言中指针的语法。 What should I do?我该怎么办?

Your question is very vague because you haven't specified what you need the pointers for.你的问题很模糊,因为你没有指定你需要什么指针。 If you need pointer arithmetic, the closest thing in Java is the Unsafe API, which is proprietary and not part of the official JDK API.如果您需要指针运算,Java 中最接近的是Unsafe API,它是专有的,不是官方 JDK API 的一部分。

If you need to just pass pointers around and dereference them, no syntax for that is needed in Java—actually you must remove the syntax from C++ code to get the equivalent in Java:如果您只需要传递指针并取消引用它们,则 Java 中不需要这样做的语法——实际上,您必须从 C++ 代码中删除语法才能在 Java 中获得等效的语法:

  • ptr->method() converts to ptr.method() ptr->method()转换为ptr.method()

  • *ptr becomes just ptr *ptr变成只是ptr

  • &obj becomes just obj . &obj变成了obj

This is because Java exclusively uses pointers to refer to objects, so the syntax simply assumes them.这是因为 Java 只使用指针来引用对象,所以语法简单地假设它们。

Firstly, there's no pointers (actually, everything, except primitives, is a pointer, but you want to change passed variable, ain't you?) in Java, so you should think of how you can implement the same functionality without pointers.首先,Java 中没有指针(实际上,除了基元,所有东西都是指针,但是您想更改传递的变量,不是吗?),因此您应该考虑如何在没有指针的情况下实现相同的功能。

If you can't succeed in this, you can make your methods accept something, which holds reference for another variable, for example, AtomicReference<T> ( AtomicInteger / AtomicLong for, correspondingly, int and long ).如果你不能成功,你可以让你的方法接受一些东西,它保存另一个变量的引用,例如, AtomicReference<T>AtomicInteger / AtomicLong ,相应地, intlong )。

It would be something like:它会是这样的:

void changeMyString(AtomicReference<String> ref) {
    ref.set("Hello, World!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM