ArraryList:
Using array implementation in the underlying.
public class ArrayList{ Object[] object = new Object(10); //when you need an ArrayList, initialize it. int size=0; //record how many Object you have add public void add(Object o){ if(size == object.length){ //before you add, judge whether the array is the max length; Object newObject = new Object(object.length*2); //if it reaches the max length, you need to add the array length dynamically. The new array's length decided on you.(J DKis not like this); System.arraycopy(object,0,newObject,0,object.length); object=newObject(); } object[size]=o; size++; } public int size(){ return size; } }
LinkedList:Using list implementation in the underlying
public class Node{ private Object data; private Node next; public Object getData(){ return data; } public Node getNext(){ return next; } public void setData(Object o){ this.data=o; } public void setNext(Node n){ this.next=n; } public Node(Object o,Node n){ super(); this.data=o; this.next=n; } }
public class LinkedList{ Node head = null; //The link's head Node tail = null; // The link's tail private int size=0; public void add(Object o){ Node n = new Node(o,null); //when you add one node , you initialize it first. if(head==null){ //if the head is null, the n you just initialized is the head; head = n; tail= head; //there is only one node, tail is the head; } tail.setNext(o); // set o in the next tail=n; //set the new node to be tail size ++; } public int size(){ return size; } }
The comment is not very clear.Hope it helps someone.