DEV Community

Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Comparable and Comparator in Java

Mobile.java

package com.payilagam.collections;

public class Mobile implements Comparable<Mobile> {

    private String brand;
    private int price;
    private int ram;

    public Mobile(String brand, int price, int ram) {
        super();
        this.brand = brand;
        this.price = price;
        this.ram = ram;
    }
    public int getPrice() {
        return price;
    }
    public void setPrice(int price) {
        this.price = price;
    }
    public int getRam() {
        return ram;
    }
    public void setRam(int ram) {
        this.ram = ram;
    }
    @Override
    public String toString() {
        return "Mobile [brand=" + brand + ", price=" + price + ", ram=" + ram + "]";
    }
    public String getBrand() {
        return brand;
    }
    public void setBrand(String brand) {
        this.brand = brand;
    }

    @Override
    public int compareTo(Mobile mobile) {
        return this.ram - mobile.ram;
    }

}

Enter fullscreen mode Exit fullscreen mode

Main.java

package com.payilagam.collections;

import java.util.ArrayList;
import java.util.Collections;

public class Main {

    public static void main(String[] args) {
        ArrayList<Mobile> shop = new ArrayList<>();
        shop.add(new Mobile("vivo",15000,6));
        shop.add(new Mobile("realme",20000,8));
        shop.add(new Mobile("oppo",25000,8));
        Collections.sort(shop);
        System.out.println(shop);









//      marks.add(89);
//      marks.add(90);
//      marks.add(78);
//      marks.add(99);
//      
//    Comparelogic logic = new Comparelogic();
//    Collections.sort(marks,logic);
//    System.out.println(marks);

    }

}

Enter fullscreen mode Exit fullscreen mode

Comparelogic.java

package com.payilagam.collections;

import java.util.Comparator;

public class Comparelogic implements Comparator<Integer> {

    @Override
    public int compare(Integer o1, Integer o2) {

        return o1 - o2;
    }

}
Enter fullscreen mode Exit fullscreen mode
[Mobile [brand=vivo, price=15000, ram=6], Mobile [brand=realme, price=20000, ram=8], Mobile [brand=oppo, price=25000, ram=8]]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)