简体   繁体   English

在一个类中创建一个HashSet,想要在另一个类中调用/读取

[英]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. 我的程序中有两个类,在一个类中,我创建了一个名为“ words”的HashSet,我需要能够从另一个类中的该HashSet进行调用,或者通过其他方式复制该HashSet。 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: 我现在想要/需要调用HashSet的代码如下:

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: 我的HashSet的代码是:

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) (HashSet的“单词”是在课程的前面定义的)

 If HashSet is non-static

Create getHashSet() method in your class containing the HashSet . 在包含HashSet的类中创建getHashSet()方法。 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. 在要访问此HashSet的类中,创建一个包含HashSet的类的新实例。 Call instance.getHashSet(); 调用instance.getHashSet();

if HashSet is static

(Its better to make it public as well..) use ClassContainingHashSet.hashSet to get hashset. (最好也将其公开。)使用ClassContainingHashSet.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. 注意:这不是确切的代码。这是示例代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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