标签:lis return break ret 长度 str link string col
Collection接口中定义的方法如下,所有继承自Collection接口的接口(List,Set)的实现类均实现了这些方法。
List容器是有序、可重复的,常用的实现类:ArrayList,LinkedList,Vector(线程安全的)
带索引的add,remove操作。
自己实现的MyArrayList:
package test.stringTest; public class MyArrayList<E> { private Object[] elementData; // 元素个数 private int size; // 数组默认长度 private final static int DEFAULT_CAPACITY = 10; public MyArrayList() { elementData = new Object[DEFAULT_CAPACITY]; } public MyArrayList(int length) { if (length <= 0) throw new RuntimeException("容器容量值需为正整数:" + length); elementData = new Object[length]; } public void add(E element) { if (size == elementData.length) grow(); elementData[size++] = element; } @SuppressWarnings("unchecked") public E get(int index) { if (indexInRange(index)) return (E) elementData[index]; else throw new RuntimeException("索引越界:" + index); } public void remove(E element) { int index = -1; for (int i = 0; i < size; i++) { if (element.equals(elementData[i])) { index = i; break; } } if (index != -1) { remove(index); } } public void remove(int index) { if (!indexInRange(index)) { throw new RuntimeException("索引越界:" + index); } int numMoved = elementData.length - index - 1; if (numMoved > 0) { System.arraycopy(elementData, index + 1, elementData, index, numMoved); } else { elementData[index] = null; } size--; } private boolean indexInRange(int index) { return index < size && index >= 0 ? true : false; } public int size() { return size; } public boolean isEmpty() { return size == 0 ? true : false; } // 数组扩容 private void grow() { Object[] newArray = new Object[elementData.length + (elementData.length >> 1)]; System.arraycopy(elementData, 0, newArray, 0, elementData.length); elementData = newArray; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < size; i++) { sb.append(elementData[i].toString() + ","); } sb.setCharAt(sb.length() - 1, ‘]‘); return sb.toString(); } public static void main(String[] args) { MyArrayList<String> list = new MyArrayList<>(20); int i = 0; while (i <= 50) { list.add("aaa" + i); i++; } System.out.println(list); System.out.println(list.get(31)); System.out.println(list.size()); list.remove(21); list.remove("aaa4"); System.out.println(list); System.out.println(list.size); System.out.println(list.isEmpty()); } }
标签:lis return break ret 长度 str link string col
原文地址:https://www.cnblogs.com/ustc-anmin/p/10911101.html