我需要一个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;
}