package com.xingtu.sdk.sdk;
public class MyArrayList<T> {
private T[] array;
private int theSize;
public MyArrayList(){
this(10);
}
private MyArrayList(int length){
try {
new Exception();
}catch (Exception e){
e.printStackTrace();
}
array = (T[]) new Object[length];
}
/**
* 添加元素
* @param t
* @return
*/
public boolean add(T t){
add(size(),t);
return true;
}
/**
* 在对应位置添加元素
* @param idx
* @param t
*/
private void add(int idx,T t){
if (array.length == size()){
//扩容
ensureCapacity(size() * 2 + 1);
}
if (idx > size())
idx = size();
array[idx] = t;
if (idx >= size()) {
theSize++;
}
}
/**
* List扩容
* @param newSize
*/
private void ensureCapacity(int newSize){
if (newSize < size()){
return;
}
T[] ot = array;
array = (T[]) new Object[newSize];
for (int i = 0;i < ot.length;i++){
array[i] = ot[i];
}
}
/**
* 移除元素
* @param idx
* @return
*/
public T reomve(int idx){
T removedItem = array[idx];
for(int i = idx; i < size()-1; i++){ //为什么不是size()
array[i] = array[i + 1];
}
theSize--;
return removedItem;
}
/**
* 设置某位置元素
* @param idx
* @param newVal
* @return
*/
public T set(int idx,T newVal){
if(idx < 0 || idx >= size()){
return null;
}else{
T old = array[idx];
array[idx] = newVal;
return old;
}
}
/**
* 获取List长度
* @return
*/
public int size(){
return theSize;
}
/**
* 判断List是否为空
* @return
*/
public boolean isEmpty(){
return size() == 0;
}
/**
* 获取对应下标元素
* @param idx
* @return
*/
public T get(int idx){
if(idx < 0 || idx >= size()){
return null;
}else{
return array[idx];
}
}
public static void main(String[] args){
MyArrayList<String> list = new MyArrayList<>();
int size = list.size();
System.out.println("size1 = "+ size);
list.add("1");
list.add("2");
list.add("3");
System.out.println("size2 = "+ list.size());
list.reomve(0);
System.out.println("size3 = "+ list.size());
}
}
Java面试题之手写ArrayList
最新推荐文章于 2024-07-11 18:56:51 发布