最近在学习数据结构和算法,书上有个ArrayList的简单实现,写的很不错。

 package cn.sp.test4;

 import java.util.Iterator;
import java.util.NoSuchElementException; /**
* Created by 2YSP on 2017/10/9.
*/
public class MyArrayList<AnyType> implements Iterable<AnyType> { private static final int DEFAULT_CAPACITY = 10; private int theSize;
private AnyType[] theItems; public MyArrayList(){
doClear();
} private void doClear() {
theSize = 0;
ensureCapacity(DEFAULT_CAPACITY);
} public int size(){
return theSize;
} public boolean isEmpty(){
return size() == 0;
} public void trimToSize(){
ensureCapacity(size());
} /**
* 获取角标处的值
* @param idx
* @return
*/
public AnyType get(int idx){
if (idx < 0 || idx >= size()){
//角标越界异常
throw new ArrayIndexOutOfBoundsException();
} return theItems[idx];
} /**
* 替换目标位置的值,并返回旧值
* @param idx
* @param newVal
* @return
*/
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;
theItems = (AnyType[]) new Object[newCapacity];
for(int i = 0 ;i < old.length ; i++){
theItems[i] = old[i];
}
} public boolean add(AnyType x){
add(size(),x);
return true;
} public void add(int idx,AnyType x){
if (theItems.length == size()){
//如果已满则扩容为之前的两倍
ensureCapacity(size()*2 + 1);
} for (int i = theSize ; i > idx ; i--){
theItems[i] = theItems[i-1];//依次后挪
} theItems[idx] = x;
theSize++;
} 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<AnyType> implements java.util.Iterator<AnyType>{ private int current = 0; @Override
public boolean hasNext() {
return current < size();
} @Override
public AnyType next() {
if (!hasNext()){
throw new NoSuchElementException();
} return (AnyType) theItems[ current++ ];
} @Override
public void remove() {
MyArrayList.this.remove(current--);
}
}
}

注意理解current++和current--

实现自己的ArrayList的更多相关文章

  1. 计算机程序的思维逻辑 (38) - 剖析ArrayList

    从本节开始,我们探讨Java中的容器类,所谓容器,顾名思义就是容纳其他数据的,计算机课程中有一门课叫数据结构,可以粗略对应于Java中的容器类,我们不会介绍所有数据结构的内容,但会介绍Java中的主要 ...

  2. 分享个 之前写好的 android 文件流缓存类,专门处理 ArrayList、bean。

    转载麻烦声明出处:http://www.cnblogs.com/linguanh/ 目录: 1,前序 2,作用 3,特点 4,代码 1,前序  在开发过程中,client 和 server 数据交流一 ...

  3. 深入理解java中的ArrayList和LinkedList

    杂谈最基本数据结构--"线性表": 表结构是一种最基本的数据结构,最常见的实现是数组,几乎在每个程序每一种开发语言中都提供了数组这个顺序存储的线性表结构实现. 什么是线性表? 由0 ...

  4. 【干货】用大白话聊聊JavaSE — ArrayList 深入剖析和Java基础知识详解(二)

    在上一节中,我们简单阐述了Java的一些基础知识,比如多态,接口的实现等. 然后,演示了ArrayList的几个基本方法. ArrayList是一个集合框架,它的底层其实就是一个数组,这一点,官方文档 ...

  5. WebAPI接口返回ArrayList包含Dictionary对象正确解析

    一.问题提出 为了减少流量,将key-value(键值对)直接输出到Dictionary<string, string>,接口返回结果如下: 其中{}里面内容如下: 上图显示600是键,4 ...

  6. ArrayList LinkedList源码解析

    在java中,集合这一数据结构应用广泛,应用最多的莫过于List接口下面的ArrayList和LinkedList; 我们先说List, public interface List<E> ...

  7. ArrayList、Vector、LinkedList的区别联系?

    1.ArrayList.Vector.LinkedList类都是java.util包中,均为可伸缩数组. 2.ArrayList和Vector底层都是数组实现的,所以,索引数据快,删除.插入数据慢. ...

  8. ArrayList、Vector、HashMap、HashSet的默认初始容量、加载因子、扩容增量

    当底层实现涉及到扩容时,容器或重新分配一段更大的连续内存(如果是离散分配则不需要重新分配,离散分配都是插入新元素时动态分配内存),要将容器原来的数据全部复制到新的内存上,这无疑使效率大大降低. 加载因 ...

  9. Java中Vector和ArrayList的区别

    首先看这两类都实现List接口,而List接口一共有三个实现类,分别是ArrayList.Vector和LinkedList.List用于存放多个元素,能够维护元素的次序,并且允许元素的重复.3个具体 ...

  10. C#语言基础——集合(ArrayList集合)

    集合及特殊集合 集合的基本信息: System.Collections 命名空间包含接口和类,这些接口和类定义各种对象(如列表.队列.位数组.哈希表和字典)的集合.System.Collections ...

随机推荐

  1. Codeforces 920G(二分+容斥)

    题意: 定义F(x,p)表示的是一个数列{y},其中gcd(y,p)=1且y>x 给出x,p,k,求出F(x,p)的第k项 x,p,k<=10^6 分析: 很容易想到先二分,再做差 然后问 ...

  2. system表空间用满解决

      分类: Oracle 早上看到alert日志报说system表空间快满了(oracle版本是11gR2):   如果system表空间不是自动扩展,空间用满甚至会出现数据库无法登陆.使用任何用户登 ...

  3. jenkins的构建日志(console output)分类解析

    每个jenkins的job构建过程中会产生大量日志,如何快速找到或者查看我们关心的日志显得很有意义,为此jenkins提供了一个插件“Log Parser Plugin”可以帮助我们完成这个任务. 1 ...

  4. java 返回json数据

    Student st1 = new Student(1, "dg", 18, new Date());            Student st2 = new Student(2 ...

  5. 【effective c++】模板与泛型编程

    模板元编程:在c++编译器内执行并于编译完成时停止执行 1.了解隐式接口和编译期多态 面向对象编程总是以显式接口(由函数名称.参数类型和返回类型构成)和运行期多态(虚函数)解决问题 模板及泛型编程:对 ...

  6. [Bash] Search for Text with `grep`

    In this lesson, we’ll use grep to find text patterns. We’ll also go over some of the flags that grep ...

  7. java 实现打印当前月份的日历

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcTc0NTQwMTk5MA==/font/5a6L5L2T/fontsize/400/fill/I0JBQk ...

  8. 将Python打印的内容进行高亮的输出

    将打印的内容进行高亮的显示 内容: 格式: echo "\033[字背景颜色;字体颜色m字符串\033[0m" 例如: "\033[41;36m something he ...

  9. shell选择语句、循环语句

    判断语句:  if 判断条件  then    语句  [elif]    [语句]  ...  [else    语句]  fi    #!/bin/bash  if [ $# -eq 0 ]  t ...

  10. UITableViewController的子控件不随着滑动

    UITableViewController的子控件不随着滑动 我们知道有时候使用UITableViewController简单便捷,省事,但是如果我们使用了addSubview,无论是[self.vi ...