【发布时间】:2015-01-18 08:51:28
【问题描述】:
我最近开始编程,所以这很容易。我很难整理我的对象。我有一个包含姓名、出生日期和电话号码的对象。像 Object[0][0]="John" Object[0][1]="10/10/2010" Object[0][0]="900000000" 和其他几个人一样。所以我的困难是按姓名排序并将出生日期和电话号码与姓名一起保留。 谢谢。
【问题讨论】:
我最近开始编程,所以这很容易。我很难整理我的对象。我有一个包含姓名、出生日期和电话号码的对象。像 Object[0][0]="John" Object[0][1]="10/10/2010" Object[0][0]="900000000" 和其他几个人一样。所以我的困难是按姓名排序并将出生日期和电话号码与姓名一起保留。 谢谢。
【问题讨论】:
合乎逻辑的做法是创建一个包含姓名、出生日期和电话号码的Person 类。然后,不要使用类型不安全的 2D Object 数组,而是使用 1D 数组 - Person[]。
如果您的 Person 类将实现 Comparable<Person>(使用比较名称的比较逻辑),Arrays.sort() 将按名称为您排序数组。
【讨论】:
这是我的标准排序示例,恰好使用了 Person 对象:
/*
** Use the Collections API to sort a List for you.
**
** When your class has a "natural" sort order you can implement
** the Comparable interface.
**
** You can use an alternate sort order when you implement
** a Comparator for your class.
*/
import java.util.*;
public class Person implements Comparable<Person>
{
String name;
int age;
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String toString()
{
return name + " : " + age;
}
/*
** Implement the natural order for this class
*/
public int compareTo(Person p)
{
return getName().compareTo(p.getName());
}
static class AgeComparator implements Comparator<Person>
{
public int compare(Person p1, Person p2)
{
return p1.getAge() - p2.getAge();
}
}
public static void main(String[] args)
{
List<Person> people = new ArrayList<Person>();
people.add( new Person("Homer", 38) );
people.add( new Person("Marge", 35) );
people.add( new Person("Bart", 15) );
people.add( new Person("Lisa", 13) );
// Sort by natural order
Collections.sort(people);
System.out.println("Sort by Natural order");
System.out.println("\t" + people);
// Sort by reverse natural order
Collections.sort(people, Collections.reverseOrder());
System.out.println("Sort by reverse natural order");
System.out.println("\t" + people);
// Use a Comparator to sort by age
Collections.sort(people, new Person.AgeComparator());
System.out.println("Sort using Age Comparator");
System.out.println("\t" + people);
// Use a Comparator to sort by descending age
Collections.sort(people, Collections.reverseOrder(new Person.AgeComparator()));
System.out.println("Sort using Reverse Age Comparator");
System.out.println("\t" + people);
}
}
【讨论】: