问题描述
我有有一个名为名称
A字符串字段的类。我有类型的数组 SomeClass的[]
,我希望通过自己的名字字符串为了这些 SomeClass的
对象迭代。
I have a class which has a String field called name
. I have an array of type SomeClass[]
and I want to iterate through these SomeClass
objects in String order on their names.
我很好奇,什么是最有效的方式做到这将是。我应该使用某种形式的比较?难道是一个好主意,把他们都变成 TreeMap的
,然后遍历通过或类似的东西?我敢肯定,我可以想出一个解决方案,但我也相信,这将低于效率。
I'm curious as to what the most efficient way to do this would be. Should I use a comparator of some sort? Would it be a good idea to put them all into a TreeMap
and then iterate through that or something similar? I'm sure I could come up with a solution, but I'm also sure that it would be less than efficient.
任何帮助是AP preciated。
Any help is appreciated.
推荐答案
把你的类在的ArrayList
,并使用其排序
方法。
未经核实的code:
Put your Classes in an Arraylist
and use its sort
method.Unverified code:
yourArray.sort(new YourNameComparator());
class YourNameComparator implements Comparator<YourNameClass> {
int compare(YourNameClass y1, YourNameClass y2) {
return y1.getName().compareTo(y2.getName());
}
}
这篇关于爪哇 - 我怎样才能最有效地排序字符串字段这些对象SomeClass的对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!