2

I wrote class that represent a Set. in the Set i have a field "elements" of ArrayList. all the methods in the class are generics.

first method i wrote is a method that get another Set as argument and returns new Set that hold the union between this.Set to the argument. here is the method:

   public Set<E> union(Set<E> s){
      Set<E> toReturn = new Set<>();

      for(E toAdd : this.elements) {
        toReturn.addToSet(toAdd);
      }
      for(E toAdd : s.elements)
        toReturn.addToSet(toAdd);

      return toReturn;
   }

Now i want to write another method that get as argument ArrayList> and returns new Set that represent the union between this.Set to all the Sets inside the argument ArrayList. but i can't get access to the Sets inside the ArrayList. here is my code:

   public Set<E> union(ArrayList<Set<E>> s) {
      Set<E> toReturn = new Set<>();

      for(E el : s) {
               toReturn.addToSet(s.union(el));
      }

      return toReturn;
   }

The compiler tell me "The method union(E) is undefined for the type ArrayList>.

I'll be happy for some help. Thanks

9
  • Why do you pass in an ArrayList of a Set<E>? Why not simply pass in a List<E>? Commented May 12, 2019 at 18:44
  • Share the code of the class with the attributs to avoid misunderstanding please Commented May 12, 2019 at 18:55
  • Are you sure you are no confusing java.util.ArrayList and java.util.Set with your code ? Commented May 12, 2019 at 18:56
  • Did you name your class Set ? You should never use a build-in name Commented May 12, 2019 at 18:59
  • @azro Since the class that the OP designed represents exactly a Set, Set should be its name. Commented May 14, 2019 at 3:45

1 Answer 1

1

You are using the wrong variable in the for loop, s is the ArrayList, and toReturn is the set that you want to calculate the union of, with the addAll(otherSet); method. You may be using the Guava's Set library if so, you can keep using the union(otherSet) method.

Where you have:

for(E el : s) {
               toReturn.addToSet(s.union(el));
      }

Better put:

for(Set<E> el : s) {
               toReturn.addToSet(toReturn.union(el));
      }
Sign up to request clarification or add additional context in comments.

2 Comments

yes i called my class "Set" because i have to realize the Set class. i changed the line to "toReturn.addToSet(toReturn.addAll(el));" but its still tell me "the method addAll(int) is undefined for the type Set<E>. I think i have to add cast to "toReturn". but i dont know how...
Then try: for(Set<E> el : s) {... So the compiler knows that el is a set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.