[英]Java Set / Collections issue
我只是從Java開始,對集合有一些相當基本的問題。 我想創建一個名為DirectedGraph的類,該類具有兩個屬性,一組頂點和一組邊。 這些集合使用的最佳數據結構是什么? 看來Java有幾種集合的實現,我可能只想使用最基本的,沒有特征的那種。
另外,當我嘗試設置屬性的vertices
和edges
出現諸如“設置無法通過類型解析”或“語法錯誤”之類的錯誤,請插入“維度”以完成“引用類型”。 這是一些代碼以及我嘗試注釋掉的其他內容:
import java.util.Collections;
public class DirectedGraph {
private Set<> vertices;
// here are some other guesses that also didn't work:
// private Set<int[]> vertices;
// private Set<Integer> vertices;
// private Set<Integer> vertices = new HashSet<Integer>();
}
這些錯誤是怎么回事?
編輯:
如果我想要一個不帶參數但將vertices
和edges
集初始化為空的構造函數,我該怎么做?
您只是缺少Set
類的import語句。 java.lang
包之外的每個類都需要顯式導入 。
import java.util.Collections;
import java.util.Set; // <-- needs to import Set to use it
public class DirectedGraph {
private Set<> vertices;
// here are some other guesses that also didn't work:
// private Set<int[]> vertices;
// private Set<Integer> vertices;
// private Set<Integer> vertices = new HashSet<Integer>(); // <-- this would need "import java.util.HashSet" to compile
}
您所有的猜測都是正確的。 您不能在此處使用原始類型,但可以使用int[]
(這不是原始類型,它是一個由int
數組組成的int
)和Integer
(與類java.lang.Object
對應)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.