3

我需要有关 Java 作业问题的帮助。我有两个袋子,比如说包含bag1字符串A、和 ,B并且包含字符串、和。我需要为这两个包的联合编写一个 BagInterface ,然后是一个类调用。CDbag2EFGHArrayBag<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);
}
4

1 回答 1

3

根据你的例子,

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;
     }
于 2012-10-09T18:28:21.953 回答