一千萬個為什麽

搜索

為什麽Java的TreeSet沒有指定其類型參數必須擴展Comparable?

e.g. The code below throws a ClassCastException when the second Object is added to the TreeSet. Couldn't TreeSet have been written so that the type parameter can only be a Comparable type? i.e. TreeSet would not compile because Object is not Comparable. That way generics actually do their job - of being typesafe.

import java.util.TreeSet;
public class TreeSetTest {
  public static void main(String [] args) {
   TreeSet t = new TreeSet(); t.add(new Object()); t.add(new Object()); } } 

最佳答案

TreeSet doesn't require its type parameter to be Comparable, because it can take an external Comparator for comparing non-Comparable values.

轉載註明原文: 為什麽Java的TreeSet沒有指定其類型參數必須擴展Comparable?