自定义实现一个java中ArrayList类。
一、顺序表是什么
顺序表是用一段物理地址连续的存储单元依次存储数据元素的线性结构,一般情况下采用数组存储。在数组上完成数据的增删查改。
二、ArrayList
代码如下:
import java.util.Arrays;
public class MyArrayList {
private int[] elem;
private int usedSize;
public MyArrayList(){
this.elem=new int[5];
}
public MyArrayList(int capacity){
this.elem=new int[capacity];
}
public boolean isFull(){
if(this.usedSize==this.elem.length){
return true;
}
return false;
}
//打印顺序表
public void dispaly(){
for (int i = 0; i <this.elem.length ; i++) {
System.out.print(this.elem[i]+" ");
}
System.out.println();
}
// 在 pos 位置新增元素
public void add(int pos, int data) {
if(isFull()){
System.out.println("顺序表已满");
return;
}
if(pos<0||pos>this.usedSize){
System.out.println("pos位置不合法");
return;
}
for (int i = this.usedSize-1; i >=pos ; i--) {
this.elem[i+1]=this.elem[i];
}
this.elem[pos]=data;
this.usedSize++;
}
public void resize(){
this.elem=Arrays.copyOf(this.elem,2*this.elem.length);
}
// 判定是否包含某个元素
public boolean contains(int toFind) {
for (int i = 0; i <this.usedSize; i++) {
if(this.elem[i]==toFind){
return true;
}
}
return false;
}
// 查找某个元素对应的位置
public int search(int toFind) {
for (int i = 0; i <this.usedSize ; i++) {
if(this.elem[i]==toFind){
return i;
}
}
return -1;
}
// 获取 pos 位置的元素
public int getPos(int pos) {
if(pos<0||pos>=this.usedSize){
return -1;
}
return -1;
}
// 给 pos 位置的元素设为 value
public void setPos(int pos, int value) {
if(pos<0||pos>=this.usedSize){
return;
}
this.elem[pos]=value;
}
//删除第一次出现的关键字key
public void remove(int key) {
int index=search(key);
if(index==-1){
System.out.println("没有");
return;
}
for (int i = index; i <this.usedSize-1 ; i++) {
this.elem[i]=this.elem[i+1];
}
this.usedSize--;
}
// 获取顺序表长度
public int size() {
return this.usedSize;
}
// 清空顺序表
public void clear(){
this.usedSize=0;
}
}
三、测试
public class TestDemo {
public static void main(String[] args) {
MyArrayList myArrayList=new MyArrayList();
MyArrayList myArrayList1=new MyArrayList(20);
myArrayList.add(0,1);
myArrayList.add(1,2);
myArrayList.add(2,3);
myArrayList.add(3,4);
myArrayList.add(6,3);//测试不合法位置
myArrayList.add(4,5);
myArrayList.add(5,6);//表满
myArrayList.dispaly();
System.out.println(myArrayList.search(4));//下标3
System.out.println(myArrayList.search(6));//无 -1
System.out.println(myArrayList.contains(6));//无 应为false
System.out.println(myArrayList.contains(2));//有 为true
myArrayList.setPos(2,5);
myArrayList.dispaly();
myArrayList.remove(5);
myArrayList.dispaly();
System.out.println(myArrayList.size());
System.out.println(myArrayList.getPos(4));
myArrayList.resize();
myArrayList.dispaly();
}
}

总结
1,增容需要申请新空间,拷贝数据,释放旧空间。会有不小的消耗。
2, 增容一般是呈2倍的增长,势必会有一定的空间浪费。例如当前容量为100,满了以后增容到200,我们再继续
插入了5个数据,后面没有数据插入了,那么就浪费了95个数据空间。
如何解决这类问题,则用到了链表(LinkedList)。
自定义链表(LinkedList)
版权声明:本文为m0_46123217原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。