簡體   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