Java中两个物件袋的联合

时间:2012-10-09 18:21:48

标签: java object interface union bag

我需要Java家庭作业问题的帮助。我有两个包,说bag1包含字符串ABCD以及bag2包含字符串EFGH。我需要为这两个包的联合编写一个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);
}

1 个答案:

答案 0 :(得分: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将使用union进行更新。

 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;
     }