comparable and comparator
import java.util.*;
class mbl implements Comparable<mbl>
{
String brand,model;
double price;
mbl(String g, String b,double d)
{
brand=g;
model=b;
price=d;
}
public int compareTo(mbl m)
{
if(price > m.price)
return 1;
else if(price == m.price)
return 0;
else
return -1;
}
}
class StockComparator implements Comparator<mbl> {
public int compare(mbl c1, mbl c2)
{
if (c1.brand.equals(c2.brand))
return 0;
else if (c1.brand.length() > c2.brand.length())
return 1;
else
return -1;
}
}
public class Q9_Mobail {
public static void main(String args[])
{
ArrayList<mbl> c = new ArrayList<>();
c.add(new mbl("jagwar","ipro",1500));
c.add(new mbl("war","max",98));
c.add(new mbl("ferari","yut",73));
c.add(new mbl("moto","rt",48523));
c.add(new mbl("sonic","erty",9200));
c.add(new mbl("preeti","fg",965));
for(mbl t:c)
{
System.out.println("price: "+t.price+" brand:"+t.brand+" model"+t.model);
}
Collections.sort(c);
System.out.println("after sorting by price:");
for(mbl t:c)
{
System.out.println("price: "+t.price+" brand:"+t.brand+" model"+t.model);
}
System.out.println("after sorting by brand:");
Collections.sort(c, new StockComparator());
for(mbl t:c)
{
System.out.println("price: "+t.price+" brand:"+t.brand+" model"+t.model);
}
}
}