我知道對java中對象的引用是通過複製傳遞的,但副本仍然指向系統中的同一內存,所以在更新另一個函數中的複雜對象的某些數據之後,應該維護原始數據。但有趣的是,這裏出了問題。我正在與Tries合作。丟失數據的複雜對象
這裏是我的執行線索的,這是因爲一些自定義的規則相當定製的實現:
public class Trie {
boolean isEnd;
Trie trie[] = new Trie[256];
ArrayList<Integer> indexNode;
public static Trie createTrieNode() {
Trie temp = new Trie();
temp.isEnd = false;
temp.indexNode = new ArrayList<Integer>();
for (int i = 0; i < temp.trie.length; i++) {
temp.trie[i] = null;
}
return temp;
}
public static void insertIntoTrie(Trie root, char[] alpha, int index, int i) {
if (root == null)
root = createTrieNode();
if (i < alpha.length)
insertIntoTrie(root.trie[alpha[i] - 'a'], alpha, index, i + 1);
else {
if (root.isEnd == true) {
root.indexNode.add(index);
} else {
root.isEnd = true;
root.indexNode.add(index);
}
}
}
}
現在我的目標root
來自這個類並在調試,我可以看到正在執行該語句:root.isEnd = true;
類:
public class AnagramsTogether {
public Trie root = new Trie();
public void printAnagrams(String[] anagrams){
char[] buffer;
for (int i = 0; i < anagrams.length; i++) {
buffer = anagrams[i].toCharArray();
Arrays.sort(buffer);
Trie.insertIntoTrie(root, buffer, i, 0);
}
AnagramsUtil.anagramUtil(root,anagrams);
}
}
但當時root
這裏傳遞的是AnagramsUtil.anagramUtil(root,anagrams);
public class AnagramsUtil {
public static void anagramUtil(Trie root, String[] anagrams) {
if (root.isEnd == true) {
for (Iterator<Integer> iterator = root.indexNode.iterator(); iterator
.hasNext();) {
Integer integer = (Integer) iterator.next();
System.out.println(anagrams[integer]);
}
} else {
for (int i = 0; i < root.trie.length; i++) {
if (root.trie[i] == null)
continue;
anagramUtil(root.trie[i], anagrams);
}
}
}
}
public class Anagram{
public static String string[] = {"cat", "dog", "god","act", "tac","gdo"};
public static void main(String args){
new AnagramsTogether().printAnagrams(Anagram.string);
}
}
本聲明if (root.isEnd == true)
從不執行,所以是這是從來沒有執行anagramUtil(root.trie[i], anagrams);
。該程序只是繼續執行continue
聲明。 不應該是這種情況,因爲我已經看到root.trie[i]
正在接收值。爲什麼會發生這種情況?我對java很陌生。
[This](http://stackoverflow.com/a/40523/645270)可以幫助 – keyser
調用'printAnagrams(String [] anagrams)'時使用了哪些參數? –
用參數編輯我的代碼。 –