我试图Set
用Java中的ArrayList实现自己的。我正在测试该add()
方法,并且某种程度上它不会在Set中添加元素。我知道,如果将一个元素添加到ArrayList中,那么List.add(input)
它将返回true,所以问题可能出在这里。有人可以帮助我了解我在做什么错吗?这是Setadd()
方法的实现:
导入java.util.ArrayList; 导入java.util.Collection;
public class Set<E> implements Collection<E> {
private ArrayList<E> List = new ArrayList<>();
public boolean add(E input) {
if (contains(input)) {
return false;
}
return List.add(input);
}
这是我运行的测试方法:
import java.util.*;
public class TestSet {
public static Set<Integer> set = new Set<Integer>();
public static void main(String[] args) {
System.out.println("Enter a set :");
Scanner userInput = new Scanner(System.in);
set = new Set<Integer>();
set.add(userInput.nextInt());
System.out.println(set);
}
运行该方法后,我在控制台上得到的输出是:
Enter a set :
1
Set@677327b6
似乎您未使用toString
方法或未正确使用方法,您需要使用:
public class Set<E> implements Collection<E> {
private ArrayList<E> list = new ArrayList<>();
...
@Override
public String toString() {
return list.toString();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句