Domanda

Ho un arraylist istituito. Ho instuctions ingresso istituito anche, in modo che l'utente può inserire una stringa, poi un intero, quindi una stringa (il nome, l'età, e il cognome).

Ho bisogno di ordinare l'ArrayList in base al cognome. Il codice che ho inserito finora è tutto sotto il principale metodo: -

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
È stato utile?

Soluzione

Date un'occhiata a paragonabile , comparatore , < a href = "http://java.sun.com/j2se/1.5.0/docs/api/java/util/Arrays.html#sort%28T[],%20java.util.Comparator%29" rel =" nofollow noreferrer "> Arrays.sort e 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());
        }
    }
}

Altri suggerimenti

Questo non vuole essere offensivo, ma vi suggerisco di imparare le basi prima di passare a Swing.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top