如何在Java中使用指针?

2022-08-31 08:01:00

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


答案 1

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...)为second提供值同样是一个潜在的错误,并可能导致丢失它所指向的对象。

当您调用 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中没有。


答案 2

由于Java没有指针数据类型,因此不可能在Java中使用指针。即使是少数专家也无法在java中使用指针。

另请参阅以下文章中的最后一点:Java 语言环境