如何在 Java 中使用指针?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1750106/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use pointers in Java?
提问by
I know Java doesn't have pointers, but I heard that Java programs can be created with pointers and that this can be done by the few who are experts in java. Is it true?
我知道 Java 没有指针,但我听说 Java 程序可以用指针创建,而且这可以由少数 Java 专家来完成。这是真的吗?
回答by Poindexter
Technically, all Java objects are pointers. All primitive types are values though. There is no way to take manual control of those pointers. Java just internally uses pass-by-reference.
从技术上讲,所有 Java 对象都是指针。尽管所有原始类型都是值。没有办法手动控制这些指针。Java 只是在内部使用按引用传递。
回答by Fortega
As Java has no pointer data types, it is impossible to use pointers in Java. Even the few experts will not be able to use pointers in java.
由于 Java 没有指针数据类型,因此在 Java 中不可能使用指针。即使是少数专家也不会在java中使用指针。
See also the last point in: The Java Language Environment
另见最后一点:Java 语言环境
回答by Andrzej Doyle
Not really, no.
不是真的,不是。
Java doesn't have pointers. If you reallywanted you could try to emulate them by building around something like reflection, but it would have all of the complexityof pointers with none of the benefits.
Java 没有指针。如果你真的想要,你可以尝试通过围绕反射之类的东西来模拟它们,但它会具有指针的所有复杂性,但没有任何好处。
Java doesn't have pointers because it doesn't need them. What kind of answers were you hoping for from this question, i.e. deep down did you hope you could use them for something or was this just curiousity?
Java 没有指针,因为它不需要它们。您希望从这个问题中得到什么样的答案,即您内心深处希望您可以将它们用于某些事情还是只是出于好奇?
回答by Yazz.com
Java does not have pointers like C has, but it does allow you to create new objects on the heap which are "referenced" by variables. The lack of pointers is to stop Java programs from referencing memory locations illegally, and also enables Garbage Collection to be automatically carried out by the Java Virtual Machine.
Java 没有像 C 那样的指针,但它允许您在堆上创建由变量“引用”的新对象。指针的缺失是为了阻止Java程序非法引用内存位置,同时也让Java虚拟机自动进行垃圾回收。
回答by coolest_head
All objects in java are passed to functions by reference copy except primitives.
Java 中的所有对象都通过引用副本传递给函数,原始对象除外。
In effect, this means that you are sending a copy of the pointer to the original object rather than a copy of the object itself.
实际上,这意味着您发送的是指向原始对象的指针的副本,而不是对象本身的副本。
Please leave a comment if you want an example to understand this.
如果您想要一个示例来理解这一点,请发表评论。
回答by Michael Myers
Java does have pointers. Any time you create an object in Java, you're actually creating a pointer to the object; this pointer could then be set to a different object or to null
, and the original object will still exist (pending garbage collection).
Java 确实有指针。任何时候在 Java 中创建对象时,实际上都是在创建指向该对象的指针;然后可以将此指针设置为不同的对象或设置为null
,并且原始对象仍将存在(等待垃圾回收)。
What you can't do in Java is pointer arithmetic. You can't dereference a specific memory address or increment a pointer.
在 Java 中你不能做的是指针运算。您不能取消引用特定的内存地址或增加指针。
If you really want to get low-level, the only way to do it is with the Java Native Interface; and even then, the low-level part has to be done in C or C++.
如果你真的想要底层,那么唯一的方法就是使用Java Native Interface;即便如此,低级部分也必须用 C 或 C++ 完成。
回答by Sajad Bahmani
All objects in Java are references and you can use them like pointers.
Java 中的所有对象都是引用,您可以像使用指针一样使用它们。
abstract class Animal
{...
}
class Lion extends Animal
{...
}
class Tiger extends Animal
{
public Tiger() {...}
public void growl(){...}
}
Tiger first = null;
Tiger second = new Tiger();
Tiger third;
Dereferencing a null:
取消引用空值:
first.growl(); // ERROR, first is null.
third.growl(); // ERROR, third has not been initialized.
Aliasing Problem:
别名问题:
third = new Tiger();
first = third;
Losing Cells:
丢失细胞:
second = third; // Possible ERROR. The old value of second is lost.
You can make this safe by first assuring that there is no further need of the old value of second or assigning another pointer the value of second.
您可以通过首先确保不再需要旧的 second 值或为另一个指针分配 second 的值来确保安全。
first = second;
second = third; //OK
Note that giving second a value in other ways (NULL, new...) is just as much a potential error and may result in losing the object that it points to.
请注意,以其他方式(NULL、new...)给 second 一个值同样是一个潜在的错误,可能会导致丢失它指向的对象。
The Java system will throw an exception (OutOfMemoryError
) when you call new and the allocator cannot allocate the requested cell. This is very rare and usually results from run-away recursion.
OutOfMemoryError
当您调用 new 并且分配器无法分配请求的单元格时,Java 系统将抛出异常 ( )。这是非常罕见的,通常是由失控递归引起的。
Note that, from a language point of view, abandoning objects to the garbage collector are not errors at all. It is just something that the programmer needs to be aware of. The same variable can point to different objects at different times and old values will be reclaimed when no pointer references them. But if the logic of the program requires maintaining at least one reference to the object, It will cause an error.
请注意,从语言的角度来看,将对象丢弃到垃圾收集器根本不是错误。这只是程序员需要注意的事情。同一个变量可以在不同的时间指向不同的对象,当没有指针引用它们时,旧值将被回收。但是如果程序的逻辑要求至少维护一个对象的引用,就会导致错误。
Novices often make the following error.
新手经常犯以下错误。
Tiger tony = new Tiger();
tony = third; // Error, the new object allocated above is reclaimed.
What you probably meant to say was:
你可能想说的是:
Tiger tony = null;
tony = third; // OK.
Improper Casting:
铸造不当:
Lion leo = new Lion();
Tiger tony = (Tiger)leo; // Always illegal and caught by compiler.
Animal whatever = new Lion(); // Legal.
Tiger tony = (Tiger)whatever; // Illegal, just as in previous example.
Lion leo = (Lion)whatever; // Legal, object whatever really is a Lion.
Pointers in C:
C中的指针:
void main() {
int* x; // Allocate the pointers x and y
int* y; // (but not the pointees)
x = malloc(sizeof(int)); // Allocate an int pointee,
// and set x to point to it
*x = 42; // Dereference x to store 42 in its pointee
*y = 13; // CRASH -- y does not have a pointee yet
y = x; // Pointer assignment sets y to point to x's pointee
*y = 13; // Dereference y to store 13 in its (shared) pointee
}
Pointers in Java:
Java中的指针:
class IntObj {
public int value;
}
public class Binky() {
public static void main(String[] args) {
IntObj x; // Allocate the pointers x and y
IntObj y; // (but not the IntObj pointees)
x = new IntObj(); // Allocate an IntObj pointee
// and set x to point to it
x.value = 42; // Dereference x to store 42 in its pointee
y.value = 13; // CRASH -- y does not have a pointee yet
y = x; // Pointer assignment sets y to point to x's pointee
y.value = 13; // Deference y to store 13 in its (shared) pointee
}
}
UPDATE:as suggested in the comments one must note that C has pointer arithmetic. However, we do not have that in Java.
更新:正如评论中所建议的那样,必须注意 C 具有指针算法。但是,我们在 Java 中没有。
回答by Jay
As others have said, the short answer is "No".
正如其他人所说,简短的回答是“不”。
Sure, you could write JNI code that plays with Java pointers. Depending on what you're trying to accomplish, maybe that would get you somewhere and maybe it wouldn't.
当然,您可以编写使用 Java 指针的 JNI 代码。取决于你想要完成什么,也许这会让你到达某个地方,也许不会。
You could always simulate pointes by creating an array and working with indexes into the array. Again, depending on what you're trying to accomplish, that might or might not be useful.
您始终可以通过创建数组并使用数组中的索引来模拟指针。同样,根据您要完成的任务,这可能有用也可能没用。
回答by Peter Lawrey
You can use addresses and pointers using the Unsafe class. However as the name suggests, these methods are UNSAFE and generally a bad idea. Incorrect usage can result in your JVM randomly dying (actually the same problem get using pointers incorrectly in C/C++)
您可以使用 Unsafe 类使用地址和指针。然而,顾名思义,这些方法是不安全的,通常是个坏主意。不正确的使用会导致你的 JVM 随机死亡(实际上同样的问题在 C/C++ 中错误地使用指针)
While you may be used to pointers and think you need them (because you don't know how to code any other way), you will find that you don't and you will be better off for it.
虽然您可能习惯于使用指针并认为您需要它们(因为您不知道如何以任何其他方式进行编码),但您会发现您不知道并且使用它会更好。
回答by Mordan
you can have pointers for literals as well. You have to implement them yourself. It is pretty basic for experts ;). Use an array of int/object/long/byte and voila you have the basics for implementing pointers. Now any int value can be a pointer to that array int[]. You can increment the pointer, you can decrement the pointer, you can multiply the pointer. You indeed have pointer arithmetics! That's the only way to implements 1000 int attributes classes and have a generic method that applies to all attributes. You can also use a byte[] array instead of an int[]
你也可以有文字的指针。你必须自己实现它们。对于专家来说,这是非常基础的;)。使用 int/object/long/byte 数组,瞧,您已经掌握了实现指针的基础知识。现在任何 int 值都可以是指向该数组 int[] 的指针。您可以增加指针,可以减少指针,可以乘以指针。你确实有指针算术!这是实现 1000 个 int 属性类并具有适用于所有属性的通用方法的唯一方法。您还可以使用 byte[] 数组而不是 int[]
However I do wish Java would let you pass literal values by reference. Something along the lines
但是我确实希望 Java 能让您通过引用传递文字值。沿线的东西
//(* telling you it is a pointer)
public void myMethod(int* intValue);
//(* telling you it is a pointer)
public void myMethod(int* intValue);