2014-11-06 19 views
0

我想移除HashSet的第一個元素並將此移除的元素指定給另一個變量。由於它的remove函數返回布爾值,所以我不能這樣做。我怎樣才能獲得它的刪除值?謝謝。 我的代碼是將從HashSet中移除的元素指定給變量

HashSet<Node> List = new HashSet<Node>(); 
    expandList.add(s); 
    while(expandList.size() > 0) 
    { 
    Node toAssigned = List.remove(s); 
    // other works related with toAssigned are here 

    } 

回答

0

Vladimir Ivanovwords

可以延長LinkedHash添加所需getIndex()方法。

只需通過使用迭代器和計數器的集合,檢查對象是否相等。如果找到了,請返回櫃檯。

,或者你可以嘗試Kiryl Ivanousolution

創建集只是將其轉換爲列表,並列出了指數得到後:

Set<String> stringsSet = new HashSet<>(); 
stringsSet.add("string1"); 
stringsSet.add("string2"); 

List<String> stringsList = new ArrayList<>(stringsSet); 
stringsList.get(0); // "string1"; 
stringsList.get(1); // "string2"; 
+0

但是是不是efcect的性能嗎?此代碼是8益智遊戲的BFS算法的一部分。我必須使用HashSet,因爲我的顧問,因爲他說arrayList太慢@mahdad – user3864949 2014-11-06 22:26:38

+0

@ user3864949: HashSet確保沒有重複項,給你一個O(1)contains()方法,但不保留順序。 ArrayList不確保沒有重複項,contains()是O(n)但您可以控制條目的順序。 – aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2014-11-06 22:29:46

+0

@ user3864949我相信使用哈希集具有比數組列表更好的性能。但你需要爲你的問題做 – aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa 2014-11-06 22:30:44

0

沒有的概念作爲序列順序的HashSet中的第一個元素未指定。也許,隊列數據結構可能更適合您的需要。

http://docs.oracle.com/javase/7/docs/api/java/util/Queue.html

如果您需要刪除從集合的元素而無需擔心,你刪除哪個元素,你可以使用以下命令:

set.iterator().next()