简体   繁体   中英

Creating a HashSet in one class, want to call/read in another class

I've got two classes in my program, in one I create a HashSet called 'words' and I need to be able to call from that HashSet in the other class, or otherwise copy the HashSet across. I'd prefer to do the former, it seems tidier, but either would be fine.

The code I have at the moment where I want/need to call the HashSet is such:

private void execute(String[] commands)
{
    String basicCommand = commands[0];
    //this is something I have used in a previous project to call from the HashSet
    for (String word : words)
    {
        if(basicCommand.equals("circle")) {
        makeACircle(commands);
        }
        if(basicCommand.equals(word))
                {EMPTY FOR NOW}
        else if(basicCommand.equals("help")) {
        printHelp();
        }
        else {
        System.out.println("Unknown command: " + basicCommand);
        }
    }
}`

And the code for my HashSet is:

public String[] getInput()
{
    System.out.print("> ");                // print prompt
    String inputLine = reader.nextLine().trim().toLowerCase();

    String[] wordArray = inputLine.split(" ");  // split at spaces

     // add words from array into hashset 
    for(String word : wordArray) {
        words.add(word);
    }
    return wordArray;
}

(The HashSet 'words' is defined earlier in the class)

 If HashSet is non-static

Create getHashSet() method in your class containing the HashSet . It returns a reference to the hashset. Create a new instance of the class containing HashSet in the class where you wanna access this HashSet. Call instance.getHashSet();

if HashSet is static

(Its better to make it public as well..) use ClassContainingHashSet.hashSet to get hashset.

EDIT :

public class MyFirstClass{

public static Set<YourType> mySet = new HashSet<yourType>();
}

class MySecondClass{
public void readHashSet()
{
  HashSet<YourType> hs = MyFirstClass.mySet;
}
}  

Note : This is not the exact code.. This is sample code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM