我如何在 Java 中使用指针?

新手上路,请多包涵

我知道 Java 没有指针,但我听说 Java 程序可以用指针创建,而且只有少数精通 Java 的人才能做到。是真的吗?

原文由 user213038 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 562
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;

取消引用 null:

 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 中没有。

原文由 Sajad Bahmani 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题