0

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
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
marialadelbario
  • 325
  • 1
  • 4
  • 19

1 Answers1

0

It seems you are not using toString method or not using it correctly you need to use :

public class Set<E> implements Collection<E> {

    private ArrayList<E> list = new ArrayList<>();
    ...
    @Override
    public String toString() {
        return list.toString();
    }
}
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
  • @Mark No it is not, you can't return `ArrayList` in a method which should return String try it and you will see – Youcef LAIDANI Jun 16 '18 at 10:28
  • @Mark usully when you use `Set set = new HashSet<>(Arrays.asList(1, 2, 3, 4)); System.out.println(set);` what you get? you get `[1, 2, 3, 4]` and not `Set [1, 2, 3, 4]` this why I use just `list.toString()` which will return `[1, 2, 3, 4]` – Youcef LAIDANI Jun 16 '18 at 10:47
  • hey thanks a lot this worked! could you please explain to me why it is necessary to override the toString() method? – marialadelbario Jun 16 '18 at 10:49
  • and about `it is necessary to override the toString()` because without it you will by default you are using the toString of `Object.toString` which will return what you get without toString – Youcef LAIDANI Jun 16 '18 at 10:55
  • 1
    sorry I got that wrong! thanks a lot for the explanation – marialadelbario Jun 16 '18 at 11:22