我需要Java作业问题的帮助。我有两个袋子,比如说包含字符串bag1ABCD和包含字符串bag2EFGH。我需要为这两个袋子的联合写一个BagInterface,然后是一个类ArrayBag<T> implements BagInterface<T>

BagInterface我在想这样的事情:

public interface BagInterface<T> {

    public T union(T[] item);
}

public class ArrayBag<T> implements BagInterface<T> {

    private final static int DEFAULT_CAP = 4;
    private int numElements;
    private T[] bag;

    public ArrayBagR(int cap) {
        bag = (T[]) new Object[cap];
        this.numElements = 0;
    }

    public T union(T[] item) {

        // Not sure how I should write this so I can pass
        // another class object in the parameter

        // Like say if I write a main to run this I could
        // do something like Bag1.union(Bag2)
        // and get something like A B C D E F G H
    }
}

喜欢说如果我有这个
public static void main(String[] args) {
    BagInterface bag1 = new ArrayBag(n);
    BagInterface bag2 = new ArrayBag(m);
    BagInterface<String> everything = bag1.union(bag2);
}

最佳答案

根据您的示例,

BagInterface bag1 = new ArrayBag(n);
BagInterface bag2 = new ArrayBag(m);
BagInterface<T> everything =  bag1.union(bag2);

调用时,union上的bag1传递bag2作为参数,
 this.bag -> represents bag1
 item in the argument represent bag2

现在您可以写点东西了。无需从此方法返回。 bag1将使用联合更新。
 public BagInterface<T> union(T[] item) {
    T[] everything = thi.bag;
    for(T elem: item){
       if(not(this.bag contains elem )){
          everything  -> add(elem);
       }
    }
    return this;
 }

请注意:这是共享概念的伪代码(不是代码)。

示例Java代码如下所示:
 public BagInterface<T>  union(T[] item) {
        List<T> unionList = Arrays.asList(this.bag);
        for(T elem: item){
           boolean present = false;
           for(T elem1: this.bag){
              if(elem1.equals(elem)){
                  present = true;
              }
           }
           if(!present){
               unionList.add(elem);
           }
        }
       this.bag = unionList.toArray(new Bag[unionList.size()]);
       return this;
     }

您还可以进一步使用List方法contains将代码简化为:
       public BagInterface<T> union(T[] item) {
        List<T> unionList = Arrays.asList(this.bag);
        for(T elem: item){
           if(!unionList.contains(elem)){
               unionList.add(elem);
           }
        }
        this.bag = unionList.toArray(new Bag[unionList.size()]);
        return this;
     }

如果您不想更新bag1内容,则应具有以下方法:
       public BagInterface<T> union(T[] item2) {
                BigInterface<T> everything = new BagArray<T>();
        List<T> unionList = Arrays.asList(this.bag);
        for(T elem: item){
           if(!unionList.contains(elem)){
               unionList.add(elem);
           }
        }
        everything.setBags(unionList.toArray(new Bag[unionList.size()]));
        return everything;
     }

08-04 07:40