Java集合类
java集合主要由两个接口派生 Collection和 Map,是集合框架的根接口![]()
Java各集合类比较
自定义LinkList
public class MyLinkList { private Node first; //链表头 private Node last; //链表尾 private int size; //链表长度 //获取链表长度 public int size() { return size; } //检查是否越界 public void checkRange(int index) { if(index<0 || index>=size) { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } } //获取index位置的节点 public Node node(int index) { Node temp = null; if(first!=null) { temp = first; for(int i=0; i<index; i++) { temp = temp.getNext(); } } return temp; } //添加 public void add(Object obj) { Node temp = new Node(); temp.setObj(obj); if(first==null) { temp.setPrevious(null); temp.setNext(null); first = temp; last = temp; }else { temp.setPrevious(last); temp.setNext(null); last.setNext(temp); last = temp; } size++; } //获取index位置的节点值 public Object get(int index) { checkRange(index); Node temp = node(index); if(temp!=null) { return temp.getObj(); } return null; } //移除index位置的节点 public void remove(int index) { checkRange(index); Node temp = node(index); if(temp!=null) { Node preTemp = temp.getPrevious(); Node nextTemp = temp.getNext(); preTemp.setNext(nextTemp); nextTemp.setPrevious(preTemp); } size--; } public static void main(String[] args) { MyLinkList list = new MyLinkList(); list.add("1"); list.add("2"); list.add("3"); list.remove(1); System.out.println(list.size()); System.out.println(list.get(1)); } }
自定义ArrayList
public class MyArrayList { Object[] elementData; int size; //当前容器存放了多少个数据 MyArrayList() { this(10); //默认数组大小为10 } //初始化数组的容量 MyArrayList(int initialCapacity) { if(initialCapacity<0) { //初始的数组容量不能小于0 try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } elementData = new Object[initialCapacity]; } //数组扩容 public void ensureCapacity() { if(size>=elementData.length) { //当数组容量不够用的时候 Object[] newElementData = new Object[elementData.length*2+1]; //新new一个数组,容量为原数组的2倍+1 System.arraycopy(elementData, 0, newElementData, 0, elementData.length); //将原数组中的数据拷贝到新数组中 elementData = newElementData; //原数组的引用重新指向新的数组,扩容完毕 } } //检查是否越界 public void checkRange(int index) { if(index<0 || index>=size) { try { throw new Exception(); } catch (Exception e) { e.printStackTrace(); } } } //数组是否为空 public boolean isEmpty() { return size==0; } //添加数据 public void add(Object obj) { ensureCapacity(); elementData[size++] = obj; } //获取index位置的数据 public Object get(int index) { checkRange(index); return elementData[index]; } //从容器中移除index位置的数据,但对象本身还在 public void remove(int index) { checkRange(index); System.arraycopy(elementData, index+1, elementData, index-1, size-index-1); size--; } public static void main(String[] args) { MyArrayList mylist = new MyArrayList(); mylist.add("a"); mylist.add("b"); mylist.remove(1); System.out.println(mylist.size); System.out.println(mylist.get(0)); System.out.println(mylist.get(1)); } }