编程语言
首页 > 编程语言> > 实践:在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 int size(){
    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 int size(){
    int count=1;
    while(rest!=null){
        rest=rest.rest;
        count+=1;
    }
    return count;
}

 

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

public int get(int i){
    if ( i ==1){
        return first;
    }
    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

标签:Java,int,list,中用,rest,数组,IntList,public,size
来源: https://www.cnblogs.com/M1stF0rest/p/14224135.html