要求:设计一个泛型类Collection,它存储object对象的集合(在数组中),以及该集合当前的大小。提供public方法isEmtpy,makeEmpty,insert,remove,isPresent.方法isPresent(x)当且仅当在集合中存在(由equals定义) 等于x的一个object时返回true
public class Collection { private Object[] obj; public Object[] getObj() { return obj; } public void setObj(Object[] obj) { this.obj = obj; } public boolean isEmpty() { return obj.length > 0 ? false : true; }; public void makeEmpty() { obj = new Object[] {}; } public void insert(Object o) { //扩展数组容量 Object[] temp = new Object[obj.length + 1]; //拷贝原有数组 for (int i = 0; i < obj.length; i++) { temp[i] = obj[i]; } //末位添加新元素 temp[obj.length] = o; obj = temp; } public boolean isPresent(Object o) { if (obj.length == 0) { return false; } //遍历判断 for (Object ob : obj) { if (o.equals(ob)) return true; } return false; } /** * <p> * 此处写的很复杂,应该有更简单的方法实现 * </p> */ public void remove(Object o) { if (obj.length == 0) { return; } int count = 0; for (int i = 0; i < obj.length; i++) { if (o.equals(obj[i])) { obj[i] = null; count++; } } Object[] temp = new Object[obj.length - count]; int i = 0; for (Object ob : obj) { if (ob != null) { temp[i] = ob; i++; } } obj = temp; } @Override public String toString() { return "obj=" + Arrays.toString(obj); } public static void main(String[] args) { Object[] ob = new Object[] { 1, 2, "haha", 4, true, 6, 3042F }; Collection test2 = new Collection(); test2.setObj(ob); System.err.println(test2.toString()); test2.insert(8); System.err.println(test2.toString()); test2.remove(4); System.err.println(test2.toString()); test2.remove("haha"); System.err.println(test2.toString()); } }
时间: 2024-10-12 17:28:04