Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a Set in Java

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?
like image 970
flexcookie Avatar asked Mar 30 '16 12:03

flexcookie


People also ask

Can I return a Set in Java?

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.

How do you return a string Set in Java?

The toString() method of Java HashSet is used to return a string representation of the elements of the Collection.

How do I return a HashSet in Java?

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.

What does return () do in Java?

Definition and Usage The return keyword finished the execution of a method, and can be used to return a value from a method.


1 Answers

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);
like image 89
Suresh Atta Avatar answered Nov 14 '22 21:11

Suresh Atta