I have a class, classA
, that has a constructor which uses objects from another class, classB
. I use these objects of classB
to form a set in classA
.
Now, I have a method in classA
that is setup to return the elements of the set created in the constructor.
This is where my issue is: I can't figure out the correct syntax to return the set 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?
It returns an integer value which is the hashCode value for this instance of the Set. This method is used to check whether the set is empty or not. This method is used to return the iterator of the set. The elements from the set are returned in a random order.
The toString() method of Java HashSet is used to return a string representation of the elements of the Collection.
Java HashSet methods Returns a shallow copy of the HashSet instance: the elements themselves are not cloned. Returns true if this set contains the specified element. Returns true if this set is empty. Adds the specified element to this set if it is not already present.
Definition and Usage The return keyword finished the execution of a method, and can be used to return a value from a method.
Scope matters. You restricted the scope of your set to constructor. Make it an instance member. You are able to return it then.
Set<classB> setElements = new HashSet<classB>();
public classA(classB x, class B y) {
setElements.add(x);
setElements.add(y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With