java数组列表内部实现_实践:在Java中用数组实现一个列表(所谓数组转集合)

I am going to create an array which is similar to the list in python by using Java.

It turns out that a very basic list is trivial to implement, as shown below:

public class IntList {

public int first;

public IntList rest;

public IntList(int f, IntList r) {

first = f;

rest = r;

}

}

Such a list is ugly to use. For example, if we want to make a list of the numbers 5, 10, and 15, we can either do:

IntList L = new IntList(5, null);

L.rest = new IntList(10, null);

L.rest.rest = new IntList(15, null);

Alternately, we could build our list backwards, yielding slightly nicer but harder to understand code:

IntList L = new IntList(15, null);

L = new IntList(10, L);

L = new IntList(5, L);

I can write a 'size' method to evaluate the size of such list by using recursion

public intsize(){if (rest==null){return 1;

}return 1+this.rest.size();

}

(In it, the code this.rest.size() can be replaced by rest.size())

I can also rewrite it in an iterative style:

public intsize(){int count=1;while(rest!=null){

rest=rest.rest;

count+=1;

}returncount;

}

If i want to get the specific item in the list, I can create a get method.

public int get(inti){if ( i ==1){returnfirst;

}else{

first=rest.first;

rest=rest.rest;return get( i -1);

}

}

How simple it is!!!

For futher info, please view :https://joshhug.gitbooks.io/hug61b/content/chap2/chap21.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值