package com.svse.myapp;
import java.util.Arrays;
import java.util.Random;
import org.junit.Test;
public class MyArrayList {
private Object[] objs = null;
private int index = 0;
public MyArrayList() {
objs = new Object[10];
}
// public MyArrayList(int i) {
// objs = new Object[i];
// }
@Test
public void myTest() {
MyArrayList myArrayList = new MyArrayList();
Random random = new Random();
for (int i = 0; i < 21; i++) {
myArrayList.add(random.nextInt(50));
}
System.out.println(myArrayList.indexOf(6));
myArrayList.printList();
}
public void add(Object obj) {
if (index == objs.length) {
this.objs = Arrays.copyOf(objs, index * 2);// System.arraycopy();
}
objs[index++] = obj;
}
public boolean delete(int index) {
if (index > this.index)
return false;
for (int i = index; i < this.index; i++) {
objs[i] = objs[i + 1];
}
this.index--;
return true;
}
public boolean set(int index, Object e) {
return this.index >= index ? true : false;
}
public void printList() {
for (int i = 0; i < index; i++) {
if (i % 5 == 0)
System.out.println();
System.out.print("objs[" + i + "] == " + objs[i] + ",\t");
}
}
public int indexOf(Object e) {
this.sort();// 使用二分法查找法,数组必须是有序且无重复的
int low = 0, height = this.index, middle;
while (low <= height) {
middle = (low + height) >> 1;
if ((int) e > (int) objs[middle])
low = ++middle; // 高半区查找
else if ((int) e < (int) objs[middle])
height = --middle;// 低半区查找
else
return middle;
}
return -1;
}
public void sort() {
for (int i = 0; i < this.index - 1; i++) {
for (int j = i + 1; j < this.index; j++) {
if ((int) this.objs[i] > (int) this.objs[j])
swap(i, j);
}
}
}
private void swap(int i, int j) {
Object temp;
temp = this.objs[i];
this.objs[i] = this.objs[j];
this.objs[j] = temp;
}
public boolean isContains(Object obj) {
return indexOf(obj) != -1;
}
public int count() {
return this.index;
}
}
ArrayList代理类
最新推荐文章于 2020-02-07 15:06:14 发布