Java ArrayList of Object Sort Example
19:03package OOP; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Scanner; import java.util.Vector; public class A { private String tenNV; private int tuoi; Scanner input = new Scanner(System.in); public A(String tenNV, int tuoi){ this.tenNV = tenNV; this.tuoi = tuoi; } public A() { } public String getTenNV() { return tenNV; } public void setTenNV(String tenNV) { this.tenNV = tenNV; } public String getTuoi() { return tuoi; } public void setTuoi(String tuoi) { this.tuoi = tuoi; } public ArrayList<A> input(int number){ ArrayList<A> alA = new ArrayList<A>(); for(int i = 0; i < number; i++){ System.out.println("tenNV:"); this.tenNV = input.nextLine(); System.out.println("tuoi:"); this.tuoi = Integer.parseInt(input.nextLine()); A a = new A(tenNV, tuoi); alA.add(a); } return alA; } @Override public String toString(){ return "tenNV: " + this.tenNV + " \ntuoi: " + this.tuoi; } }
package arraylist; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import OOP.A; public class ArrayListDemo extends A{ public ArrayListDemo(){ } public static void SortArrayList(ArrayList<A> alA){ Comparator<A> compalA = new Comparator<A>() { @Override public int compare(A obj1, A obj2) { // so sanh chuoi // muon sap xep nguoc lai thi doi lai vi tri cua obj1 va obj2 return obj1.getTenNV().compareToIgnoreCase(obj2.getTenNV()); /* * Sap xep so * if(obj1.getTuoi() - obj1.getTuoi() > 0){ return 1; } else if(obj1.getTuoi() - obj1.getTuoi() < 0){ return -1; } else { return 0; } * * */ } }; Collections.sort(alA, compalA); } public static void displayData(ArrayList<A> alA){ for(A a : alA){ System.out.println(a.toString()); } } public static void main(String[] args) { ArrayListDemo alDemo = new ArrayListDemo(); ArrayList<A> alA = new ArrayList<A>(); alA = alDemo.input(3); SortArrayList(alA); displayData(alA); } }
0 nhận xét