Arrlist的重要方法重写

时间:2021-04-18 03:40:06
 import java.util.Arrays;

 public class ArrayOperator {

     public static void main(String[] args) {
// TODO Auto-generated method stub
ArrList list = new ArrList();
list.add(5);
list.add(7);
list.add(6);
System.out.println(list.sizeof());
// list.remove(0);
list.insert(1, 7);
System.out.println(list.toString());
System.out.println(list.search(6)); } }
class ArrList{
//定义元素个数
private int size = 0;
//初始定义数组
private int[] data = new int[10];
public ArrList(){
}
public ArrList(int inificapacity){ //初始化数组容量的构造方法
if(inificapacity < 0){
throw new ArrayIndexOutOfBoundsException();
}else {
data = new int[inificapacity];
}
}
public boolean isEmpty(){ //判断数组是否为空操作
return size ==0;
}
public void grow(){ //判断元素是否需要扩容
if(data.length <=1){
data = Arrays.copyOf(data, data.length+1);
}else{
data = Arrays.copyOf(data, data.length+data.length>>1);
} }
public void add(int element){ //增加元素操作
if(size >= data.length){
this.grow();
}else{
data[size++] = element;
}
}
public void insert(int index,int element){ //插入元素操作
if(index < 0){
throw new ArrayIndexOutOfBoundsException();
}else if(index <= size){
for(int i = size-1; i >= index;i--){
data[i+1] = data[i];
} data[index] = element;
size++; }else{
throw new ArrayIndexOutOfBoundsException();
}
}
public void remove(int index){
if(index < 0){
throw new ArrayIndexOutOfBoundsException();
}
else if(index < size){
for(int i = index; i < data.length-1;i++){
data[i] = data[i+1];
}size--;
}else{
throw new ArrayIndexOutOfBoundsException();
}
}
public int search(int element){ for(int i = 0; i < size;i++){
if(data[i] == element){ return i;
}
}
return -1;
}
public int ele(int index){
if(index < 0 || index >= size){
throw new ArrayIndexOutOfBoundsException();
}else{
return data[index];
}
}
public int sizeof(){
return size;
}
public void clear(){
data = new int[10];
size = 0;
}
@Override
public String toString(){
StringBuilder str = new StringBuilder("[");
for(int i = 0 ;i < size ;i++){
str.append(data[i]).append(",");
}
String sb = str.toString();
if(size > 0){
sb= sb.substring(0,sb.length()-1);
}
return sb + "]";
}
}