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

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

当您调用new并且分配器无法分配所请求的单元时,Java系统将抛出异常(OutOfMemoryError)。这是非常罕见的,通常是由于run-away递归。

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

新手经常出现以下错误。

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、付费专栏及课程。

余额充值