我必须使用集合(不是 Java 内置的集合)来创建 Bag 类。我无法为此找出 equal() 方法。基本上它需要检查两个包的大小是否相同,为它们创建副本,使用联合来连接它们,并在 for 循环中检查当前值是否在每个包中;如果是这样,请删除它们。如果两个袋子都是空的,那么它们是相等的。出于某种原因,代码不断吐出错误?
我为所有的代码道歉,但很难确定要漏掉什么,因为大部分代码是一致的。
谢谢大家的帮助!!
编辑:这也伴随着这个问题:Building a bag class in Java
public class Bag<t> implements Plan<t>{
private final int MAX = 10;
private final int DEFAULT = 6;
private static Random random = new Random();
private t[] content;
private int count;
//Constructors
public Bag(){
count = 0;
content = (t[]) (new Object[DEFAULT]);
}
public Bag(int capacity){
count = 0;
if(capacity<MAX)
content = (t[])(new Object[capacity]);
else System.out.println("Capacity must be less then 10");
}
//Implemented Methods
public void add(t e) {
try{
if(!contains(e) && (!(size() == content.length))){
content[count] = e;
count++;
}
}catch (ArrayIndexOutOfBoundsException exception){
System.out.println("Bag is Full");
}
}
public boolean isEmpty() {
return count==0;
}
public boolean contains(t e) {
Object location = null;
for(int i=0;i<count;i++)
if(content[i].equals(e)) location=i;
return (location!=null);
}
public int size() {
return count;
}
public void addAll(Bag<t> b) {
for (int i=0;i<b.size();i++)
add(b.content[i]);
}
public Bag<t> union(Bag<t> a, Bag<t> b) {
Bag<t> bigBag = new Bag<t>();
for(int i=0; i<a.size();i++)
bigBag.add(a.content[i]);
for(int k=0; k<b.size();k++)
bigBag.add(b.content[k]);
return bigBag;
}
public boolean equals(Bag<t> e) {
Bag<t> bag1 = new Bag<t>();
Bag<t> bag2 = new Bag<t>();
Bag<t> bag3 = new Bag<t>();
t object;
if(size() == e.size()){
bag1.addAll(this);
bag2.addAll(e);
bag3.union(bag1, bag2);
for(int i=0; i<bag3.size();i++){
object = bag3.content[i];
if((bag1.contains(object)) &&(bag2.contains(object))){
bag1.remove(object);
bag2.remove(object);
}
}
}
return (bag1.isEmpty()&&(bag2.isEmpty()));
}