ArrayList类的实现
来源:互联网 发布:如何利用网络找客户 编辑:程序博客网 时间:2024/05/16 12:49
- import java.util.Iterator;
- import java.util.NoSuchElementException;
- public class MyArrayList<AnyType> implements Iterable<AnyType> {
- private static final int DEFAUTL_CAPACITY = 10;
- private int theSize;
- private AnyType[] theItems;
- public MyArrayList() {
- clear();
- }
- public void clear() {
- theSize = 0;
- ensureCapacity(DEFAUTL_CAPACITY);
- }
- public int size() {
- return theSize;
- }
- public boolean isEmpty() {
- return size() == 0;
- }
- public void trimToSize() {
- ensureCapacity(size());
- }
- public AnyType get(int idx) {
- if (idx < 0 || idx >= size())
- throw new ArrayIndexOutOfBoundsException();
- return theItems[idx];
- }
- public AnyType set(int idx, AnyType newVal) {
- if (idx < 0 || idx > size())
- throw new ArrayIndexOutOfBoundsException();
- AnyType old = theItems[idx];
- theItems[idx] = newVal;
- return old;
- }
- public void ensureCapacity(int newCapacity) {
- if (newCapacity < theSize)
- return;
- // 为数组分配内存,并将旧内容拷贝到新数组中
- AnyType[] old = theItems;
- // 因为创建泛型数组是非法的,所以创建一个泛型类型界限的数组,然后使用一个数组进行类型转换
- // 这将产生一个编译器警告,但在泛型集合的实现中这是不可避免的
- // 可用注解@SuppressWarnings("unchecked")解除警告
- theItems = (AnyType[]) new Object[newCapacity];
- for (int i = 0; i < size(); i++)
- theItems[i] = old[i];
- }
- // 添加到表的末端病通过调用添加到指定位置的较一般的版本而得以简单的实现
- public boolean add(AnyType x) {
- add(size(), x);
- return true;
- }
- /*
- * 计算上来说是昂贵的,因为它需要移动在指定位置上或指定位置后面的那些元素到一个更高的位置上
- */
- public void add(int idx, AnyType x) {
- // add方法可能要求增加容量,扩充容量的代价也是很大的
- if (theItems.length == size())
- ensureCapacity(size() * 2 + 1);
- for (int i = theSize; i > idx; i--)
- theItems[i] = theItems[i - 1];
- theItems[idx] = x;
- theSize++;
- }
- // remove方法类似于add,只是由高位置向低位置移动
- public AnyType remove(int idx) {
- AnyType removedItem = theItems[idx];
- for (int i = idx; i < size() - 1; i++)
- theItems[i] = theItems[i + 1];
- theSize--;
- return removedItem;
- }
- @Override
- public Iterator<AnyType> iterator() {
- return new ArrayListIterator();
- }
- private class ArrayListIterator implements Iterator<AnyType> {
- private int current = 0;
- @Override
- public boolean hasNext() {
- return current < size();
- }
- @Override
- public AnyType next() {
- if (!hasNext())
- throw new NoSuchElementException();
- return theItems[current++];
- }
- @Override
- public void remove() {
- MyArrayList.this.remove(--current);
- }
- }
- }
- ArrayList类的实现
- ArrayList类的实现
- ArrayList类的实现
- 自己实现一个ArrayList,模仿ArrayList类的底层结构
- JavaScript实现的ArrayList类[原创]
- java之List的实现类ArrayList
- Java集合ArrayList实现类的总结
- 模仿ArrayList类的内部实现
- ArrayList的实现原理
- ArrayList的实现
- ArrayList的实现原理
- ArrayList的实现原理
- ArrayList的实现
- ArrayList的实现原理
- ArrayList的实现原理
- ArrayList的实现原理
- ArrayList的实现原理
- 对 arraylist的实现
- 转:JS执行后台代码
- 类反射的简单的例子
- Hibernate_day3
- Struts1.X day1
- instanceof操作符
- ArrayList类的实现
- ThinkPHP中RBAC的权限控制之配置文件2
- 《草根》原创连载-面向对象之射雕英雄传
- 纠结.....
- 笔记开通了
- sql实验二:使用分组,排序,汇总
- tomcat在XP或者win7下面不能启动的问题
- 对话框
- C#前台JS和后台交互问题