我需要Java作业问题的帮助。我有两个袋子,比如说包含字符串bag1
,A
,B
和C
的D
和包含字符串bag2
,E
,F
和G
的H
。我需要为这两个袋子的联合写一个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;
}