1. Product class
1 Public classProduct2 {3 Private intpid;4 PrivateString name;5 Private DoublePrice ;6 7 PublicProduct ()8 {9 //TODO auto-generated Constructor stubTen } One A PublicProduct (intPID, String name,DoublePrice ) - { - This. PID =pid; the This. Name =name; - This. Price =Price ; - } - + Public intgetpid () - { + returnpid; A } at - Public voidSetpid (intpid) - { - This. PID =pid; - } - in PublicString getName () - { to returnname; + } - the Public voidsetName (String name) * { $ This. Name =name;Panax Notoginseng } - the Public DoubleGetPrice () + { A returnPrice ; the } + - Public voidSetprice (DoublePrice ) $ { $ This. Price =Price ; - } - the}
2. Class Comparator: Overriding the Compare method
1 Public classMycompareImplementsComparator<product>//generic <Product> indicates that the comparer can only compare Product types2 {3 4 @Override5 Public intCompare (product P1, product p2)6 {7 if(P1.getprice () <P2.getprice ())8 {9 return-1;Ten } One Else if(P1.getprice () >P2.getprice ()) A { - return1; - } the Else - //If the price is the same, sort by ID - { - if(P1.getpid () <p2.getpid ()) + { - return-1; + } A Else if(P1.getpid () >p2.getpid ()) at { - return1; - } - Else - { - return0; in } - } to } + -}
3. Using comparators in ArrayList
1 Public classProductsort2 {3 Public Static voidMain (string[] args)4 {5 6Product P1 =NewProduct (1, "Popcorn Phone", 1000000.00);7Product P2 =NewProduct (2, "IPhone 7s", 5088.00);8Product P3 =NewProduct (3, "Xiaomi 5s", 1999.99);9Product P4 =NewProduct (4, "NIIT course", 12800.00);TenProduct P5 =NewProduct (5, "Patek Philippe", 1980000.00); OneProduct P6 =NewProduct (6, "Ma Electric", 1999.99); AProduct P7 =NewProduct (7, "Tiin course", 12800.00); - //Get array Prep sort -product[] Proarr ={p1, p2, p3, P4, P5, P6, p7}; the -Arrays.sort (Proarr,NewMycompare ()); - - for(Product P:proarr) + { -System.out.println (P.getpid () + "" + p.getname () + "" ++P.getprice ()); A } at } -}
java--class Comparator