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