自定义字符串长度比较器:我的错误是什么? [英] Custom String Length Comparator: what's my mistake?

查看:198
本文介绍了自定义字符串长度比较器:我的错误是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个自定义比较器,通过长度对我的对象的名称(String)变量进行排序。

I defined a custom comparator to sort the name(String) variable of my objects by length.

下面是我的person类的代码:

Here's the code from my person class:

class MyNameLengthCompare implements Comparator<Person> {

        @Override
        public int compare(Person a, Person b) {
            if(a.getName().length() > b.getName().length()) {
                return -1;
            } else if (a.getName().length() < b.getName().length()) {
                return 1;
            } else
                return 0;
        }

    }

Collections.sort(personList,new MyNameLengthCompare); 然后我添加到我的TreeSet myTreeSet.addAll(personList)

Then in my main method I called Collections.sort(personList, new MyNameLengthCompare); and then I added it to my TreeSet myTreeSet.addAll(personList)

但它没有按名称长度排序:(

But its not sorting by length of name :(

推荐答案

你不需要在将它添加到树集之前对它进行排序,唯一重要的是树集是否具有比较器。

You don't need to sort it before you add it to the tree set. The only thing that matters is whether or not the tree set has the comparator.

这篇关于自定义字符串长度比较器:我的错误是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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