我有一个arraylist设置。我也设置了输入说明,以便用户可以输入一个字符串,然后输入一个整数,然后输入一个字符串(名字,年龄和姓氏)。

我需要按姓氏对arraylist进行排序。到目前为止,我输入的代码都在main方法下:

public static void main(String[] args) {
Name Name[] = new Name[50];
int count = 0;

for (int i=0; i<50; i++)
  NewName[i] = new Name();

//ADD NEW TO ARRAYLIST NAME
String FName = JOptionPane.showInputDialog("first name");
int age = Integer.parseInt(JOptionPane.showInputDialog("age"));
String LName = JOptionPane.showInputDialog("last name");
          NewName[count] = new Name(FName, age, LName);
count = count++;
}

//ITEMS SORT BY LAST NAME
//CODE FOR SORT GOES HERE

最佳答案

看看ComparableComparatorArrays.sortCollections.sort

import java.util.Arrays;


class Name implements Comparable<Name> {

    private String lastName;
    //Other fields

    public Name(String lastName){
        this.lastName = lastName;
    }

    public int compareTo(Name o) {
        //Null checks etc
        return lastName.compareTo(o.lastName);
    }
    public String getLastName(){
        return lastName;
    }
    //Getter and setter methods
}

public class Test{
    public static void main(String[] args) {
        Name[] arr = new Name[]{new Name("AAC"), new Name("AAD"), new Name("AAA"),new Name("ABC"), new Name("AADDE")};
        Arrays.sort(arr);
        for(Name nm:arr){
            System.out.println(nm.getLastName());
        }
    }
}

关于java - 用Java语言对数组列表进行排序,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2439299/

10-14 15:38