[Java] Design Pattern--ArraryList and LinkedList. A simple to achieve. For novice

本文介绍了两种常见的Java集合类——ArrayList和LinkedList的实现原理。ArrayList使用数组作为底层存储结构,通过动态调整数组大小来实现元素的增删。而LinkedList则采用链表结构,每个节点包含数据和指向下一个节点的指针,适用于频繁插入和删除操作。
摘要由CSDN通过智能技术生成

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.





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值