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;

取消引用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.

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

first = second;

second = third; //OK

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

OutOfMemoryError当您调用new并且分配器无法分配所请求的单元格时,Java系统将引发异常()。这是非常罕见的,通常是由于失控的递归导致的。

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

新手经常会犯以下错误。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值