- In real-world projects, you often encounter sorting problems, sorting the collection for basic data type Java support Arrays.sort () and Collection.sort (), but sorting the user-defined types? Java provides us with two solutions.
One: By implementing comparable<object> in-house implementation
Example code:
PackageCom.lky.model;Importjava.io.Serializable; @SuppressWarnings ("Serial") Public classStudentImplementsSerializable, comparable<student> { PrivateString name; PrivateInteger ID; PrivateString log; PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicInteger getId () {returnID; } Public voidsetId (Integer id) { This. ID =ID; } PublicString GetLog () {returnlog; } Public voidsetlog (String log) { This. log =log; } @Override PublicString toString () {return"Student [name=" + name + ", id=" + ID + ", log=" + log + "]"; } @Override Public intcompareTo (Student o) {returnO.getid ()-ID; }}
Two. Defining collations by implementing comparator<object>
Example code:
Packagecom.lky.test;Importjava.util.ArrayList;Importjava.util.Arrays;Importjava.util.Collections;ImportJava.util.Comparator;Importjava.util.List;ImportJava.util.Random;Importorg.junit.Test;Importcom.lky.model.Student; Public classCompartortest { Public classOutcomparatorImplementsComparator<student>{@Override Public intCompare (Student O1, Student O2) {intresult = 0; Result= O1.getid ()-O2.getid (); if(Result = = 0) { returno1.getname (). CompareTo (O2.getname ()); } Else { returnresult; } }} @Test Public voidTest () {List<Student> array =NewArraylist<student>(); for(inti = 0; I < 20; ++i) {Student Student=NewStudent (); Student.setid (NewRandom (). Nextint (10) + 1); Student.setlog ("Log" +i); Student.setname ("Lky" +i); Array.add (student); } collections.sort (array);//Use default sort//Collections.sort (Array, new Outcomparator ());//Use custom sorting for(Student student:array) {System.out.println (Student); } }}
java--Object Comparer