我的 Java 任务是使用数组实现集合类。
作业不允许我从库中导入集合类,所以我必须自己制作。当我尝试打印数组时,它会重复打印数字,不是唯一的数字。我不知道问题出在哪里,所以如果你们能在我的代码中找到任何错误,那就太好了。我尝试将数字 2、3 和 4 添加到集合中,因此结果应该是 2 3 4
,但代码显示了 2 3 2 3 2
。
我认为问题的根源在于set类的add方法,但我不知道问题到底是什么。
import java.util.Arrays;
public final class Set implements SetInterface
{
private int[] set;
private int size;
private int capacity;
public Set(int c)
{
capacity = c;
set = new int[capacity];
size = 0;
}
public boolean contains(int x)
{
boolean contains = false;
for(int i = 0; i<capacity; i++)
{
if(x == set[i])
contains = true;
else
contains = false;
}
return contains;
}
public void add(int x)
{
for(int i = 0; i<capacity; i++)
{
if(!contains(x))
{
if(size == capacity)
{
set = Arrays.copyOf(set,size*2);
}
if(set[i]==0)
{
set[i++] = x;
}
}
}
size++;
}
public boolean remove(int x)
{
boolean remove = false;
for(int i = 0; i < capacity; i++)
{
if(x == set[i])
{
set[i] = set[size -1];
size--;
remove = true;
}
if(isEmpty())
{
remove = false;
}
}
return remove;
}
public void clear()
{
set = null;
size = 0;
}
public int size()
{
return size;
}
public boolean isEmpty()
{
if(size == 0)
return true;
else
return false;
}
public int[] toArray()
{
return Arrays.copyOf(set, capacity);
}
}
这是我测试我的类的驱动程序类。
import java.util.Arrays;
public class SetDriver
{
public static void main(String[] args)
{
SetDriver driver = new SetDriver();
Set s1 = new Set(5);
s1.add(2);
s1.add(3);
s1.add(4);
driver.print(s1);
System.out.println("Size: "+s1.size());
}
public static void print(Set s)
{
for(int i = 0; i<s.toArray().length; i++)
{
System.out.print(s.toArray()[i]+" ");
}
System.out.println("");
}
}
输出在这里:
2 3 2 3 2
Size: 3
最佳答案
您的 contains
方法可能存在问题。假设您确实找到了重复项。发生的情况是,您将变量分配给 true
,然后继续迭代。这完全颠覆了逻辑;您可以有一个重复项,但永远不要对其进行操作,因为您的 boolean 代码阻止您这样做。
理想情况下,当您找到匹配项时,您必须停止迭代并立即返回。
public boolean contains(int value) {
for(int setItem : set) {
if(setItem == value) {
return true;
}
}
return false;
}
关于java - 使用数组实现 Set 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383483/