是collections.sort方法只用于List类型的集合? [英] is collections.sort method only used for List type of collections?

查看:373
本文介绍了是collections.sort方法只用于List类型的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友,我是新的Java收集。我想问: Collections.sort()方法只用于/ 列表类型的集合。我无法排序以下代码:

friends, I am new to Java-Collection. I want to ask does Collections.sort() method only used for/by collections which are List type. I was unable to sort following code:

Collection collection=new HashSet();
collection.add("zebra");
collection.add("frog");
collection.add("bison");
collection.add("puma");
Collections.sort(collection); //error...why??

我知道 HashSet 元素。

推荐答案

错误是因为Collections类只支持一个List。

The error is because the Collections class only supports a List.

public static <T extends Comparable<? super T>> void sort(List<T> list)

要排序你的集合, / p>

To sort your collection, you can try something like:

Collection collection=new HashSet();
collection.add("zebra");
collection.add("frog");
collection.add("bison");
collection.add("puma");
ArrayList<String> temp = new ArrayList<String>(collection);
Collections.sort(temp);
collection = new HashSet(temp);

希望这有帮助。

这篇关于是collections.sort方法只用于List类型的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆