How to return a set in Java

I have a classA class that has a constructor that uses objects from another classB class. I use these classB objects to form a collection in classA . Now I have a method in classA that is configured to return the elements of the set created in the constructor.

This is where my problem is: I cannot figure out the correct syntax to return the given elements.

This is my code:

 package testing; import java.util.*; public class classA { public classA(classB x, classB y) { Set<classB> setElements = new HashSet<classB>(); setElements.add(x); setElements.add(y); public set<classB> getElements() { return setElements; //THIS IS WHERE MY ERROR IS. HOW DO I RETURN A SET? 
+6
source share
1 answer

Scope You have limited the scope of your set to a constructor. Make it a member of the instance. Then you can return it.

  Set<classB> setElements = new HashSet<classB>(); public classA(classB x, class B y) { setElements.add(x); setElements.add(y); 
+10
source

All Articles