2015-04-20 46 views
1

我有一個叫Node的類。對於Node的一個實例,我想指定一個字典作爲屬性來跟蹤Node對象的鄰居,以及連接Node到每個鄰居的路徑的權重。我可以將字典分配爲另一個類實例的屬性嗎?

實施例:

1-> 2 --- 7(節點1連接到節點2,其重量的7)

1-> 3 --- 5(節點1連接到節點3具有重量的5)

...

我想創建一個節點對象「1」,其具有與(鍵,值)相等(鄰,重量)一個字典屬性。

在這種情況下,1的字典應該是[2:7,3:5]。

import java.util.Dictionary; 

public class Node{ 

    public int i; 
    public Dictionary neighbors = new Dictionary(); 
    public int w; 

    public Node(int i, int j, int weight){ 
     this.i = i; 
     this.neighbors = neighbors.put(j, weight); 

    } 
} 

當前錯誤:./Node.java:6:錯誤:字典是抽象的;不能實例化

這可能嗎?如果是這樣,它會怎樣?

回答

1

From the docs

The Dictionary class is the abstract parent of any class, such as Hashtable , which maps keys to values.

NOTE: This class is obsolete. New implementations should implement the Map interface, rather than extending this class.

使用Map

Map<Node, Integer> neighbors = new HashMap<>(); 

// ... 

neighbors.put(j, weight); 
+0

工作!感謝:) – Josh

0

你不能實例化一個抽象類。這並不意味着你不能將它作爲實例變量的類型。

但是,您需要實現Dictionary的子類,而不是Dictionary本身。

public Dictionary neighbors = new Dictionary(); 

應該

public Dictionary neighbors = new DictionarySubClass(); 

另外:這是很好的做法,讓您的實例變量私有,並使用存取器(getter和setter)操縱它們。

+2

沒有'Dictionary'作爲'DictionarySubClass'。但是快速瀏覽一下[javadoc](http://docs.oracle.com/javase/7/docs/api/java/util/Dictionary.html)可以提供兩件事情。 1)'Dictionary'的唯一實現是'Hashtable',並且2)'Dictionary'被棄用。 –

+0

@BoristheSpider:這只是一個如何處理抽象類的例子,這是他遇到的問題。據我所知,喬什創建了一個DictionarySubClass,所以我不能說沒有一個。 這並不意味着「複製和它會工作」的解決方案,而是「這裏是想法如何...」 – Stultuske

+0

承認這可能都是真的,但我會假設某人誰不知道什麼一個'抽象類'最有可能不會自己實現'Dictionary'。您已經在這裏回答了XY問題,並忽略了潛在的問題。這有助於在回答初學者提出的問題時嘗試和解決_intent_。 –

相關問題