如何访问不同类 Java 中的私有变量



我有一个类,拼写检查,它(以及各种其他东西(从"交互"窗口中给出的文件名创建一个trie。例如.txt当我输入java SpellCheck small时,我知道创建了一个词典/字典,因为它在拼写检查中由其他方法显示。

public class SpellCheck{
 // the dictionary
 private LexiconTrie dict;

 // Constructor;  creates window elements
 public SpellCheck(String[] files) {
  dict = new LexiconTrie(files); 
我需要在我的另一个类 LexiconTrie 中

访问该 LexiconTrie 字典中的信息(迭代、根、节点等(。但是,每当我尝试访问它时(即使使用 SpellCheck.dict,它也会给我"dict 在拼写检查中具有私有访问权限"(或类似的内容(的错误。

在这种情况下,我是否不完全理解私有/公共类交互?(如果我没有提供足够的信息,请告诉我(---------编辑/更新

---------------------

这是拼写检查中的方法

public void doAutoComplete() {
  Collection<String> arr = dict.getCompletions(curText.trim().toLowerCase(), num_value);
  String intro = "Up to " + num_value + " completions";
  display(arr, "No matches found", intro);   
}

我需要在LexiconTrie中编写方法getCompletions()。我的教授为我们实现了一个GUI界面。此 GUI 界面创建一个搜索栏,每当用户在搜索栏中键入字母时,该搜索栏都会调用doAutoComplete。在LexiconTrie中,我应该编写getCompletions以返回在LexiconTrie dict中找到的匹配项("完成"((在拼写检查中私下创建和存储(。

我看到这是按照以下思路编写方法:

// Method you have to implement
public Collection<String> getCompletions(String lowerCase, int max) {
  String searchWord = lowerCase;
  int maxReturned = max;
  LinkedList trieMatches = new LinkedList();

  // this is as far as I got, it won't even print the search word. 
 // I get an error from trying to look into dict with .containsWord
  if (dict.containsWord(searchWord)){
    System.out.println(searchWord); 
    //add word/prefix to LinkedList
    //add all children and their children up until max#
  }
  else{
    return null;
  }
}
我需要在我的另一个类 LexiconTrie 中

访问该 LexiconTrie 字典中的信息(迭代、根、节点等(。

这似乎很奇怪(不过,如果不看到更多代码,很难说(。

通常,您不希望访问LexiconTrie的另一个实例,而是希望在this上进行操作。

所以而不是

void someMethod(SpellCheck spellCheck){
    spellCheck.dict.something();
}

你会有

void someMethod(){
    something();
}
// called from spellcheck as
this.dict.someMethod();

创建一个访问私有变量的方法:

public LexiconTrie getDict(){
  return dict;
}

最新更新