2016-08-05 60 views
1

我正在尝试使用现有HashSet和其中的数据创建TreeSet。 但我无法找到一个重载的方法,我可以通过一个外部比较器?如何使用现有HashSet和其中的数据创建TreeSet?

有没有办法可以在创建TreeSet时使用外部比较器?

public static void main(String[] args) { 

     Set<Bus> m = new HashSet<>(); 
     Bus b1 = new Bus(1, "bhl", "udr"); 
     Bus b2 = new Bus(2, "ahmd", "mum");   
     m.add(b1); 
     m.add(b2); 
     //Below will create treeset using default comparable logic. 
     Set<Bus> treeObject = new TreeSet<>(m); 

     // There is no overloaded constructor like this. 
     Set<Bus> treeObject = new TreeSet<>(m, new BusComparator()); 

我该如何做到这一点?

回答

1

你可以做的两个步骤:

Set<Bus> treeObject = new TreeSet<>(new BusComparator()); 
treeObject.addAll(m); 
+1

如果你看看源代码,毕竟对方是什么构造函数是干什么的,:'公共TreeSet的(集合 C){这个();的addAll(C); }' – Andreas

相关问题