要求:设计一个泛型类Collection,它存储object对象的集合(在数组中),
以及该集合当前的大小。提供public方法isEmtpy,makeEmpty,insert,remove,isPresent.方法isPresent(x)当且仅当在集合中存在(由equals定义) 等于x的一个object时返回true
import java.util.Arrays;
/**
* 可以用
* @author 疯狂龅牙酥
*
*/
public class One_thirteen {
public static void main(String[] args) {
// TODO Auto-generated method stub
Object[] obj = new Object[] {"9"};
Collection<String> cool = new Collection<String>(obj);
System.out.println(Arrays.toString(cool.getCollection()));
System.out.println(cool.getSize());
System.out.println(cool.isEmpty());
System.out.println(cool.getSize());
cool.makeEmpty();
System.out.println(cool.isEmpty());
System.out.println(cool.getSize());
cool.insert("1");
cool.insert("2");
cool.insert("3");
System.out.println(Arrays.toString(cool.getCollection()));
System.out.println(cool.getSize());
cool.remove(2);
System.out.println(Arrays.toString(cool.getCollection()));
System.out.println(cool.getSize());
System.out.println(cool.isPresent("3"));
}
}
class Collection<Value> {
private Object[] arr;
private int size = 0; // 0为空
public Collection(Object[] arr) {
this.size = arr.length;
this.arr = arr;
}
public int getSize() {
return this.size;
}
public Object[] getCollection() {
return this.arr;
}
public boolean isEmpty() {
return this.size == 0;
}
public void makeEmpty() {
this.size = 0;
// 这里应该把数组清空
this.arr = new Object[] {};
}
public void insert(Value insertedValue) {
if (this.size > this.arr.length + 1) {
// 还能装
this.arr[this.size++] = insertedValue;
} else {
// 装不下了,需要开辟空间
// 先开辟一块更大的,然后替换掉原来的,原来的系统会自动回收垃圾空间
Object[] tmp = new Object[this.size + 1];
System.arraycopy(this.arr, 0, tmp, 0, this.size++);
tmp[this.size - 1] = insertedValue;
this.arr = tmp;
}
}
public void remove(int index) {
if(index < 0 || index > this.size-1) {
return;
}
if(index < this.size-1) {
for(int i=index; i<this.size-1; i++) {
this.arr[i] = this.arr[i+1];
}
}
Object[] tmp = new Object[this.size-1];
System.arraycopy(this.arr, 0, tmp, 0, index);
System.arraycopy(this.arr, index+1, tmp, index, this.size-1-index);
this.arr = tmp;
this.size--;
}
public boolean isPresent(Value v) {
for(Object vi:this.arr) {
if(vi.equals(v)) {
return true;
}
}
return false;
}
}