I am trying to implement my own Set
with an ArrayList in Java. I am testing the add()
method and somehow it wont add the elements in the Set. I know that if an element is added in the ArrayList then List.add(input)
will return true, so maybe the problem lies there. Can someone help me understand what I am doing wrong?
This is the implementation of the Set add()
method:
import java.util.ArrayList; import 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);
}
And this is the test method I run :
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);
}
The output I get on the console after running the method is:
Enter a set :
1
Set@677327b6