设计一个泛型类Collection

2021-10-05  本文已影响0人  TomRidder

设计一个泛型类Collection,它存储object对象的集合(在数组中),以及该集合当前的大小。提供public方法isEmtpy,makeEmpty,insert,remove,isPresent.方法isPresent(x)当且仅当在集合中存在(由equals定义) 等于x的一个object时返回true

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Collection<AnyType> {
    private Object[] data;

    private int size;

    public Object[] getData() {
        return data;
    }

    public void setData(Object[] data) {
        this.data = data;
    }

    public boolean isEmpty() {
        return data.length==0;
    }

    public void makeEmpty() {
        data = new Object[]{};
    }

    public void insert(AnyType obj) {
        Object[] temp = new Object[data.length+1];
        System.arraycopy(data,0,temp,0,data.length);
        temp[data.length] = obj;
        data = temp;
    }

    public void remove(int index) {
        if (index<0) {
            return;
        }
        Object[] temp = new Object[data.length-1];
        System.arraycopy(data,0,temp,0,index);
        System.arraycopy(data,index+1,temp,index,data.length-index-1);
        data = temp;
    }

    public void remove(AnyType obj) {
        if (data == null || obj == null) {
            return;
        }
        Object[] temp = new Object[data.length-1];
        for (int i=0;i< data.length;i++) {
            if(data[i]==obj){
                System.arraycopy(data,0,temp,0,i);
                System.arraycopy(data,i+1,temp,i,data.length-i-1);
                data=temp;
            }
        }
    }

    public boolean isPresent(AnyType x) {
        for(int i = 0; i< data.length; i++) {
            return data[i].equals(x);
        }
        return false;
    }

    public static void main(String[] args) {
        int i =0;
        Collection<String> collectionTest = new Collection<>();
        Object[] objects =new Object[]{"9"};
        collectionTest.setData(objects);
        collectionTest.insert("1");
        collectionTest.insert("2");
        collectionTest.insert("3");
        System.err.println(Arrays.toString(collectionTest.getData()));
        collectionTest.remove(0);
        System.err.println(Arrays.toString(collectionTest.getData()));
        collectionTest.remove("2");
        System.err.println(Arrays.toString(collectionTest.getData()));
        boolean flag = collectionTest.isEmpty();
        System.err.println("isEmpty: "+flag);
        boolean flag1 = collectionTest.isPresent("1");
        System.err.println("isPresent: "+flag1);
        collectionTest.makeEmpty();
        boolean flag2 = collectionTest.isEmpty();
        System.err.println("isEmpty: "+flag2);
    }
}

image.png
上一篇 下一篇

猜你喜欢

热点阅读