ArrayList数据结构的实现
2024-08-25 21:18:02
import java.util.Iterator;
import java.util.NoSuchElementException; public class MyArrayList<T> implements Iterable<T> {
//默认数组大小
private static final int DEFAULT_CAPACITY=;
//表大小
private int theSize;
//数组存储
private T[] theItems;
//初始化表
public MyArrayList(){
doClear();
}
private void doClear() {
// TODO Auto-generated method stub
theSize=;
ensureCapacity(DEFAULT_CAPACITY);
}
//清空表
public void Clear(){
doClear();
}
//判断是否为空
public boolean isEmpty(){
return size()==;
}
//将此 ArrayList 实例的容量调整为列表的当前大小
public void trimToSize(){
ensureCapacity(size());
} public T get(int index){
if(index<||index>size()){
throw new ArrayIndexOutOfBoundsException();
}
return theItems[index];
}
public T set(int index,T val){
if(index<||index>size()){
throw new ArrayIndexOutOfBoundsException();
}
T old=theItems[index];
theItems[index]=val;
return old;
}
public boolean add(T val){
add(size(),val);
return true;
}
public void add(int index, T val) {
// TODO Auto-generated method stub
if(theItems.length==size()){
ensureCapacity(size()*+);
}
for(int i=theSize;i>index;i--){
theItems[i]=theItems[i-];
}
theItems[index]=val;
theSize++;
}
public T remove(int index){
T removedItem=theItems[index];
for(int i=index;i<size()-;i++){
theItems[i]=theItems[i+];
}
theSize--;
return removedItem;
}
public java.util.Iterator<T> iterator(){
return new ArrayListIterator();
}
private class ArrayListIterator implements java.util.Iterator<T>{
private int current=;
public boolean hasNext(){
return current<size();
}
public T next(){
if(!hasNext()){
throw new NoSuchElementException();
}
return theItems[current++];
}
public void remove(){
MyArrayList.this.remove(--current);
}
}
private void ensureCapacity(int newCapacity) {
// TODO Auto-generated method stub
if(newCapacity<theSize){
return;
}
T[] old=theItems;
theItems=(T[]) new Object[newCapacity];
for(int i=;i<size();i++){
theItems[i]=old[i];
}
}
private int size() {
// TODO Auto-generated method stub
return theSize;
} }
最新文章
- 1、Python基础知识
- 漫谈iOS程序的证书和签名机制
- Seafile内部云盘
- 车销送货上门专用无线开单器-自带PDA无线移动开单系统 与云服务器连接
- iOS开发过程中,触控板的使用技巧
- python 内存监控模块之memory_profiler
- Yahoo, Steve blog
- sysobjects.xtype介绍
- AVFoundation--AVPlayer
- Android 屏幕相关概念(1)
- 【NOIP2011TG】solution
- XmlSerializer 实现序列化CDATA
- jmeter性能测试的小小实践
- docker启动centos7后sudo不能使用
- rpm方式安装MySQL5.1.73
- iOS开发--图片轮播
- Apache HttpComponents 通过代理发送HTTP请求
- WdatePicker设置日期范围
- linux 下的mysql 连接报错
- fastjson处理json