ArrayList未按预期打印

时间:2015-02-10 10:19:47

标签: java arraylist

我有一个简单的ArrayList,它似乎没有按照我想要的方式打印。我有一个类名Person,如下所示:

public class Person {
public String Name;
public String Ni;
public String Dob;

public Person(String name, String ni, String dob){
    this.Name = name;
    this.Ni = ni;
    this.Dob = dob;
}

public String toString()
{
    return this.Name + " " + this.Ni + " " + this.Dob;
}
}

然后打印我只是做的列表

 public static void main(String []args){

    ArrayList<Person> myList = new ArrayList();

    myList.add(new Person("John Smith","123456789","01/01/1990"));
    myList.add(new Person("John Test","9876543211","15/05/1984"));
    myList.add(new Person("Some Person","147852369","15/05/1991"));

    for(Person person : myList)
    {
        System.out.println(person);
    }

 }

它按预期打印列表但是我试图按Dob下降,但我似乎无法弄清楚如何实现这一目标。我在实施Collections.sort课程后尝试了Person,但仍有同样的问题。

实际结果:

  

John Smith 123456789 01/01/1990

     

John Test 9876543211 15/05/1984

     

Some Person 147852369 15/05/1991

Desired Reasult:

  

John Test 9876543211 15/05/1984

     

John Smith 123456789 01/01/1990

     

Some Person 147852369 15/05/1991

如果有人可以帮我解决这个问题,我将非常感激。

3 个答案:

答案 0 :(得分:1)

myList.add(new Person("John Test","9876543211","15/05/1984"));
myList.add(new Person("John Smith","123456789","01/01/1990"));
myList.add(new Person("Some Person","147852369","15/05/1991"));

这样添加因为arrayList使用索引来获取数据。 0是John Smith,因为您首先将其添加到列表中。迭代0时首先在for循环中打印

答案 1 :(得分:0)

如果我理解正确你想要按出生日期排序,那么(不是&#34;下降&#34;)?您需要使您的类实现Comparable接口能够排序(或将Comparator的实现传递给sort方法)。

选项1:

public class Person implements Comparable<Person> {
    public String Name;
    public String Ni;
    public String Dob;

    public Person(String name, String ni, String dob){
        this.Name = name;
        this.Ni = ni;
        this.Dob = dob;
    }

    @Override
    public int compareTo(Person person) {
        return Dob.compareTo(person.getDob()); // you really want to compare by who is younger here right? whatever it is, put it here instead of String compare
    }

    public String getDob() {
        return Dob;
    }

    public String toString()
    {
        return this.Name + " " + this.Ni + " " + this.Dob;
    }
}

然后你可以调用Collections.sort(myList);

替代方案,使用Collections.sort(myList, comparator)并在那里提供比较器。匿名内部类实现的示例:

Collections.sort(myList, new Comparator<Person>() {
    @Override
    public int compare(Person p1, Person p2) {
        return 0; // do your comparson here
    }
});

答案 2 :(得分:0)

public class PersonAgeComparator implements Comparator<Person>
{
    public int compare(Person p1, Person p2)
    {
        return p1.getAge() - p2.getAge();
    }
}

要调用您将使用的排序:

Collections.sort(people, new PersonAgeComparator());

您会在以下链接中找到有用的信息。

https://himanshugpt.wordpress.com/2010/09/10/sorting-list-in-java/

希望这会有所帮助:)