2017-09-06 19 views
0

我試圖用下面的代碼創建一個TreeSet實例。爲什麼last()和first()方法在java中的Set Interface中不存在

Set<Integer> treeSet = new TreeSet<>(); 
treeSet.last() //gives compilation error 
//solution here is either to cast the treeSet instance 
//Or create treeSet using TreeSet concrete class. Which is not a best practice. 

這裏要做什麼?提前致謝。

+0

將這個解決問題了嗎? https://stackoverflow.com/questions/9322405/converting-a-treeset-to-arraylist –

回答

4

既然你需要SortedSet接口的方法,改變treeSetSortedSet類型做:

SortedSet<Integer> treeSet = new TreeSet<>(); 
treeSet.last(); 
1

設置數據結構行爲不適用於排序元素。所以SET沒有這些方法。 TreeSet中是因爲它已經訂購與

集融合+紅黑樹

數據結構來實現的機制來實現這一功能的中間道路。

SortedSet是爲此目的而開發的另一個實現。

它使用

SortedSet<Integer> set = new TreeSet<>(); 
set.last(); 
0

設置界面沒有第一個()&最後的()方法,所以使用TreeSet類型

import java.util.TreeSet; 

public class Main { 
    public static void main(String[] args) { 
     TreeSet<Integer> treeSet = new TreeSet<>(); 
     treeSet.last(); 
    } 
} 
3

Set interface沒有這些方法。其他數據結構(如HashSet)實現了Set接口,它們不保證順序,因此這些方法沒有用處。

您可以使用類,而不是接口

TreeSet<Integer> treeSet = new TreeSet<>(); 
+0

我可以補充一點,'集合'不是爲'last()','first'設計的: '它模擬數學設置抽象。 Set接口只包含從Collection繼承的方法,並添加了禁止重複元素的限制。' 集合本身不提供這些方法 –

0

的一組表示不包含重複元素的集合。因此該接口只允許獲取設置和迭代操作。

爲了自己的目標繼續使用TreeSet的(它實現的SortedSet)

TreeSet<Integer> treeSet = new TreeSet<>(); 
0

在你的代碼treeSetSet型不具備firstlast方法。如果你將與一個TreeSet工作,你將有機會獲得這些方法:

TreeSet<Integer> treeSet = new TreeSet<>(); 
treeSet.last() //gives compilation error 
//solution here is either to cast the treeSet instance 
//Or create treeSet using TreeSet concrete class. Which is not a best practice. 
0

Set接口是不被認爲是有序的集合。儘管在課堂級別上並不明確,但它完全在課程的各個方面,例如iterator()

返回此集合中元素的迭代器。這些元素以特定的順序返回(除非這個集合是某個提供擔保的類的實例)。

爲了有一個firstlast,您需要一個訂單或索引,並且兩者都不是。正如許多其他人已經指出的那樣,如果您想訂購,您可以使用SortedSet

TreeSet實現SortedSet,所以你當然可以修改您提供的代碼:

SortedSet<Integer> treeSet = new TreeSet<>(); 
treeSet.last(); 
相關問題