12、自己实现的ArrayList
2016-09-26 19:29
316 查看
1、自己实现的ArrayList的代码如下
2、参考的博客地址
http://blog.csdn.net/fenglibing/article/details/14166011
package com.baowei.test; public class MyArrayList<E> { // 表示当前的存储元素的大小 private int size = 0; // 表示容量的大小 private int capacity = 10; // 数值,用于保存数据 private E[] values = null; // 无参构造函数 @SuppressWarnings("unchecked") public MyArrayList() { values = (E[]) new Object[capacity]; } // 有参构造函数 @SuppressWarnings("unchecked") public MyArrayList(int capacity) { this.capacity = capacity; values = (E[]) new Object[capacity]; } public void add(E e) { if (e == null) { throw new RuntimeException("输入的元素为Null..."); } if (size >= capacity) { // 重新构造大小 enlargeCapacity(); } // 放入元素 values[size] = e; size++; } public E get(int index) { if (index < 0 || index >= size) { throw new RuntimeException("下标异常... "); } // 放入元素 return values[index]; } public E remove(int index) { if (index < 0 || index >= size) { throw new RuntimeException("下标异常... "); } for (int i = index; i < size - 1; i++) { values[i] = values[i + 1]; } values[size - 1] = null; size--; return values[index]; } @SuppressWarnings("unchecked") private void enlargeCapacity() { capacity = capacity * 2; E[] tmpValues = (E[]) new Object[capacity]; System.arraycopy(values, 0, tmpValues, 0, size); values = tmpValues; } public String toString() { StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < size; i++) { sb.append(values[i]).append(","); } if (size > 0) { sb.deleteCharAt(sb.length() - 1); } sb.append("]"); return sb.toString(); } public static void main(String[] args) { MyArrayList<String> myList = new MyArrayList<String>(); myList.add("0"); myList.add("1"); myList.add("2"); myList.add("3"); myList.add("4"); myList.add("5"); myList.add("6"); myList.add("7"); myList.add("8"); myList.remove(7); System.out.println(myList.toString()); } }
2、参考的博客地址
http://blog.csdn.net/fenglibing/article/details/14166011
相关文章推荐
- 自己动手重新实现LINQ to Objects: 12 - DefaultIfEmpty
- 自己动手实现ArrayList和LinkedList
- 自己实现一个ArrayList,模仿ArrayList类的底层结构
- 自己实现一下ArrayList
- 自己动手系列——实现一个简单的ArrayList
- 自己理解的java.util.ArrayList(二)实现类
- Java -- 自己实现数组列表(Arraylist)
- MyArrayList——自己实现ArrayList
- Java中SJBArrayList自己简单实现ArrayList
- Java之实现自己的ArrayList与LinkedList
- 数据结构—顺序表(自己实现Java的ArrayList)
- 自己实现ArrayList内存代码
- 实现自己的ArrayList和HashMap
- 实现自己的ArrayList和HashMap
- <仅是自己做笔记。。。系列15>实现一个挺高级的字符匹配算法: 给一串很长字符串,要求找到符合要求的字符串,例如目的串:123 1******3***2 ,12*****3这些都要找出来
- 自己动手重新实现LINQ to Objects: 12 - DefaultIfEmpty
- 实现自己的ArrayList和HashMap
- 容器第三课,JDK源码分析,自己实现ArrayList数组扩容
- ArrayList和HashMap如何自己实现实例详解
- 自己实现 ArrayList