Pergunta

Eu tenho uma configuração de Arraylist. Também tenho instituições de entrada configuradas, para que o usuário possa inserir uma string, depois um número inteiro, depois uma string (o primeiro nome, a idade e o sobrenome).

Eu preciso classificar o Arraylist pelo sobrenome. O código que eu digitei até agora está tudo sob o método principal:-

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
Foi útil?

Solução

Take a look at Comparable, Comparator, Arrays.sort and Collections.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());
        }
    }
}

Outras dicas

This isn't meant to be offensive but I would suggest you learn the basics before you move on to Swing.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top