gpt4 book ai didi

java - 如何在 Java 中使用指针?

转载 作者:IT老高 更新时间:2023-10-28 11:27:31 25 4
gpt4 key购买 nike

我知道 Java 没有指针,但我听说 Java 程序可以使用指针创建,并且这可以由少数 Java 专家来完成。是真的吗?

最佳答案

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;

解除对空值的引用:

first.growl();  // ERROR, first is null.    
third.growl(); // ERROR, third has not been initialized.

别名问题:

third = new Tiger();
first = third;

丢失的细胞:

second = third; // Possible ERROR. The old value of second is lost.    

您可以通过首先确保不再需要 second 的旧值或为另一个指针分配 second 的值来确保安全。

first = second;
second = third; //OK

请注意,以其他方式(NULL、new...)给第二个值同样是一个潜在的错误,并可能导致丢失它指向的对象。

当你调用 new 并且分配器无法分配请求的单元格时,Java 系统会抛出异常(OutOfMemoryError)。这是非常罕见的,通常是由于递归失控造成的。

请注意,从语言的角度来看,将对象丢弃到垃圾收集器根本不是错误。这只是程序员需要注意的事情。同一个变量可以在不同的时间指向不同的对象,当没有指针引用它们时,旧值将被回收。但是如果程序的逻辑需要维护至少一个对象的引用,就会报错。

新手常犯如下错误。

Tiger tony = new Tiger();
tony = third; // Error, the new object allocated above is reclaimed.

你可能想说的是:

Tiger tony = null;
tony = third; // OK.

不正确的类型转换:

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.

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
}

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
}
}

更新: 正如评论中所建议的,必须注意 C 具有指针算法。但是,我们在 Java 中没有。

关于java - 如何在 Java 中使用指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1750106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com