Java 将 ArrayList 转换为有序集合(TreeSet)并返回
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23137758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Converts ArrayList into a sorted set (TreeSet) and returns it
提问by Good tree
I a method that takes a list of numbers (e.g. ArrayList
) and converts it into a sorted set (e.g. TreeSet
) and returns it. I wrote code, but I'm having some problems.
我是一个方法,它接受一个数字列表(例如ArrayList
)并将其转换为一个有序集合(例如TreeSet
)并返回它。我写了代码,但我遇到了一些问题。
public TreeSet getSort (ArrayList list){
TreeSet set =new TreeSet(list);
return set;
My problem is in main:
我的问题主要是:
ArrayList List = new ArrayList();
List.add(5);
List.add(55);
List.add(88);
List.add(555);
List.add(154);
System.out.println("the TreeSet of ArrayList is : " + getSort(List));
采纳答案by Nambi
You need to have the class instance to call the getSort()
method or make the getSort()
to static
你需要有类的实例来调用getSort()
方法,或使getSort()
以static
Do like
喜欢
System.out.println("the TreeSet of ArrayList is : "+ new classname().getSort(List));
or make the method static
或使方法静态
public static TreeSet getSort (ArrayList list){
TreeSet set =new TreeSet(list);
return set;
}
回答by arshajii
You're probably getting an error because getSort()
isn't static
, so it can't be called from main()
. Beyond this, you shouldn't use raw types, parametrize your lists and sets:
您可能会收到错误,因为getSort()
is not static
,因此无法从 调用它main()
。除此之外,你不应该使用原始类型,参数化你的列表和集合:
ArrayList<Integer> list = ...
TreeSet<Integer> set = ...
You should be getting warnings about this.
您应该收到有关此的警告。
In fact, I would make this method totally generic:
事实上,我会让这个方法完全通用:
public static <V extends Comparable<V>> TreeSet<V> getSort(List<V> list) {
return new TreeSet<>(list);
}
Lastly, remember to follow naming conventions: local variable names should start with a lowercase letter (i.e. list
and not List
).
最后,请记住遵循命名约定:局部变量名称应以小写字母开头(即list
而不是List
)。
回答by Anubian Noob
getSort()
isn't static and can't be called from main. You need to make it static.
getSort()
不是静态的,不能从主调用。你需要让它静态。