今天学习顺序表结构心血来潮。
请大家不要嘲笑我, 还在学习阶段。功能不可能有ArrayList那样强大。
哪里逻辑不对请多指正谢谢!!!!!!!
实现的方法:
public void add(E e, Integer index)
public void add(E e)
public E remove(Integer index)
public E remove(Object obj)
public E set(E e, Integer index)
public E get(Integer index)
public Integer containt(Object obj)
public boolean clear()
public int getSize()
源码
package com.LZ;
/**
*
* @author LiuZhe 2019/3/24
*
*/
@SuppressWarnings("unchecked")
public class MyList<E> {
//默认数组的大小
private int DEFAULCAPACITY = 10;
//记录MyList对象的元素个数
private int size = 0;
private E[] array = null;
//MyList的默认构造函数 容量为10
public MyList() {
array = (E[]) new Object[DEFAULCAPACITY];
}
public MyList(int capacity) {
array = (E[]) new Object[capacity];
}
// /**
// *
// * @return 元素的个数
// */
// public int getSize() {
// //i作为计数器
// int i = 0;
// for (E e : array) {
// if(e!=null) {
// i++;
// }
// }
//
// return i;
// }
/**
* 元素个数加1
*/
private void increment() {
size++;
}
/**
* 元素个数减1
*/
private void decrement() {
size--;
}
/**
*
* @return 返回Mylist大小
*/
public int getSize() {
return size;
}
/**
* 是否容量已满或者元素个数少于扩容后的1/2
*/
public void checkArray() {
//数组是否已满
if(size >= array.length) {
//先将数组内的元素暂时存储
E[] t = (E[]) new Object[DEFAULCAPACITY];
t = array;
//将容量扩大到二倍
DEFAULCAPACITY <<= 1;
array = (E[]) new Object[DEFAULCAPACITY];
//用数组复制
System.arraycopy(t, 0, array, 0, t.length);
}
// if(size < array.length/2) {
//
// }
}
/**
* 添加元素
* @param 要添加的对象
*/
public void add(E e) {
checkArray();
//将元素添加到数组
array[size] = e;
increment();
}
/**
* 添加元素到指定位置
* @param 插入的元素
* @param 元素插入第几个位置 0是第一个位置
*/
public void add(E e, Integer index) {
//没有指定index或者index>MyList+1 复杂度低
if(index == null || index == size+1) {
add(e);
}else {
checkArray();
for(int j = size; j >= index; j--) {
array[j+1] = array[j];
}
//将元素插入到指定位置
array[index] = e;
}
//容量+1
increment();
}
/**
* 按位置删除元素
* @param index 元素的位置
* @return 返回删除的元素
*/
public E remove(Integer index) {
E e= array[index];
for(int j = index; j < size-1; j++) {
array[j] = array[j+1];
}
decrement();
return e;
}
/**
*
* @param index
* @return 返回要删除元素所在的位置 找到返回位置 找不到返回null
*/
public Integer remove(Object obj) {
Integer a = null;
for(int i = 0; i < size ; i++) {
if(array[i].equals(obj) || array[i] == obj) {
a = i;
for(int j = i; j < size-1; j++) {
array[j] = array[j+1];
}
}
}
decrement();
return a;
}
/**
*
* 元素替换
* @param e 新元素
* @param index 位置
* @return 替换掉的元素
*/
public E set(E e, Integer index) {
E t = array[index];
array[index] = e;
return t;
}
/**
*
* @param 是否存在的元素
* @return
*/
public Integer containt(Object obj) {
Integer a = null;
for(int i = 0; i < size; i++) {
if(array[i].equals(obj) || array[i] == obj) {
a = i;
break;
}
}
return a;
}
/**
* 清空
* @return
*/
public boolean clear() {
array = null;
return true;
}
/**
*
* @param index元素的位置 0是第一个位置
* @return 返回元素
*/
public E get(Integer index) {
return array[index];
}
}