繁体   English   中英

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

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

我的程序中有两个类,在一个类中,我创建了一个名为“ words”的HashSet,我需要能够从另一个类中的该HashSet进行调用,或者通过其他方式复制该HashSet。 我宁愿做前者,看起来比较整洁,但也可以。

我现在想要/需要调用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);
        }
    }
}`

我的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;
}

(HashSet的“单词”是在课程的前面定义的)

 If HashSet is non-static

在包含HashSet的类中创建getHashSet()方法。 它返回对哈希集的引用。 在要访问此HashSet的类中,创建一个包含HashSet的类的新实例。 调用instance.getHashSet();

if HashSet is static

(最好也将其公开。)使用ClassContainingHashSet.hashSet获取哈希集。

编辑:

public class MyFirstClass{

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

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

注意:这不是确切的代码。这是示例代码。

暂无
暂无

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

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