爪哇 - 我怎样才能最有效地排序字符串字段这些对象SomeClass的对象数组? [英] Java - How can I most-efficiently sort an array of SomeClass objects by a String field in those objects?

查看:138
本文介绍了爪哇 - 我怎样才能最有效地排序字符串字段这些对象SomeClass的对象数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有有一个名为名称 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的对象数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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