在Java中设置对象中的对象? [重复]

时间:2022-09-10 20:29:51

This question already has an answer here:

这个问题在这里已有答案:

I know that we can use TreeSet to sort Strings and numbers in an natural order. What if there is a Set of objects?

我知道我们可以使用TreeSet以自然顺序对字符串和数字进行排序。如果有一组对象怎么办?

For example:

I have a Person class
{
     private String firstName;
     private String lastName;
     private int age;

}

Set person = new TreeSet();

设置person = new TreeSet();

I want person sorted by firstName when I initialize person.

我想在初始化人时按firstName排序的人。

1 个解决方案

#1


1  

Both Comparable and Comparator work for you, but I suggest Comparator because it doesn't require you modify Person class, you only need the write an implementation class based on the sorting attribute, therefore Comparator is much more flexiable:

Comparable和Comparator都适合你,但我建议使用Comparator,因为它不需要你修改Person类,你只需要根据sorted属性编写一个实现类,因此Comparator更灵活:

import java.util.Comparator;
public class FirstNameComparator implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        String name1 = o1.getFirstName();
        String name2 = o2.getFirstName();
        return name1.compareTo(name2);
    }

}

//instantiate TreeSet instance with FirstNameComparator
Set<Person> ts = new TreeSet<>(new FirstNameComparator());

#1


1  

Both Comparable and Comparator work for you, but I suggest Comparator because it doesn't require you modify Person class, you only need the write an implementation class based on the sorting attribute, therefore Comparator is much more flexiable:

Comparable和Comparator都适合你,但我建议使用Comparator,因为它不需要你修改Person类,你只需要根据sorted属性编写一个实现类,因此Comparator更灵活:

import java.util.Comparator;
public class FirstNameComparator implements Comparator<Person> {

    @Override
    public int compare(Person o1, Person o2) {
        String name1 = o1.getFirstName();
        String name2 = o2.getFirstName();
        return name1.compareTo(name2);
    }

}

//instantiate TreeSet instance with FirstNameComparator
Set<Person> ts = new TreeSet<>(new FirstNameComparator());