0

I am trying to implement my own Set with an ArrayList in Java. I have written the method add() which is responsible for adding a new element in the Set, the method contains, which returns true if an element is found in the Set and the method addAll , which I want to add all the elements which the collection in the parameter contains in the Set. Despite that, when I create two objects of the class Set and invoke the method on the i get an error message on Eclipse saying : The method addAll(Collection) in the type Set is not applicable for the arguments Set .This is the code I have written for the implementation so far:

import java.util.ArrayList;
import java.util.Collection;

public class Set<E>{
private ArrayList<E> List = new ArrayList<>();

public boolean add(E e) {
    if(contains(e))
        return false;
    return List.add(e);
}

public boolean addAll(Collection<E> e) {
    for(E i : e)
    {
        if(!List.contains(i)) {
            List.add(i);
        }   
    }
    return true;
}
 public boolean contains(E e) {
    return List.contains(e);
}

This is the class from which I instantiate the objects and the method invoking I do on them:

public class NewClass
{   
   private Set setOne;
   private Set setTwo;

 public static void main(String[] args) { 
    setOne.addAll(setTwo);
}

Can someone help me understand what I am doing wrong? Thanks in advance

marialadelbario
  • 325
  • 1
  • 4
  • 19
  • Very simply, your "Set" isn't a Set. It's your own, completely unrelated class that you happened to name "S-e-t"" :( You can use explicit namespaces to disambuguate your "Set" from "java.util.collection.Set". Or, better, 'java.util.Set`. – paulsm4 Jun 15 '18 at 20:56

1 Answers1

3

Your Set does not implement the java.util.Collection interface. Thus, your Set is not a Collection.

The Collection interface requires quite some methods to be implemented, but if you let your Set<E> implements Collection<E> and implement all required methods, your code will work.

As a quick&dirty fix, you could add a method public boolean addAll(Set<? extends E> set) to your Set.

Some remarks on your code:

  • Following the PECS mnemonic, you may want to change the signature of your existing addAll(...) method to:

    public boolean addAll(Collection<? extends E> e)
    
  • In Java, varialbe-, attribute- and method-names should start with a lowercase letter (private ArrayList<E> List = new ArrayList<>(); -> private ArrayList<E> list = new ArrayList<>();).

  • You should give your variables and parameters meaningful names (e.g. collection instead of e or entry instead of i).

  • It is regarded as bad practice to neglect optional parentheses around if-, else-, for-, ... bodies.

Turing85
  • 18,217
  • 7
  • 33
  • 58