Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.List;
- public class Program {
- public static void main(String[] args) {
- List<Laptop> laps = new ArrayList<Laptop>();
- laps.add(new Laptop("Dell", 4, 1000));
- laps.add(new Laptop("Acer", 2, 1500.50));
- laps.add(new Laptop("Asus", 8, 1070));
- laps.add(new Laptop("HP", 16, 1400));
- Comparator<Laptop> comp = new Comparator<Laptop>()
- {
- @Override
- public int compare(Laptop l1, Laptop l2) {
- if (l1.getRam() < l2.getRam()) {
- return 1;
- } else if (l1.getRam() > l2.getRam()) {
- return -1;
- }
- return 0;
- }
- };
- Collections.sort(laps, comp);
- for(Laptop lap : laps) {
- System.out.println(lap);
- }
- System.out.println(laps.getClass());
- }
- }
- public class Laptop implements Comparable<Laptop>{
- private String model;
- private int ram;
- private double price;
- public Laptop(String model, int ram, double price) {
- this.model = model;
- this.ram = ram;
- this.price = price;
- }
- public String getModel() {
- return model;
- }
- public void setModel(String model) {
- this.model = model;
- }
- public int getRam() {
- return ram;
- }
- public void setRam(int ram) {
- this.ram = ram;
- }
- public double getPrice() {
- return price;
- }
- public void setPrice(double price) {
- this.price = price;
- }
- @Override
- public String toString() {
- return "Laptop [model=" + model + ", ram=" + ram + ", price=" + price + "]";
- }
- @Override
- public int compareTo(Laptop other) {
- if (this.getPrice() > other.getPrice()) {
- return -1;
- } else if (this.getPrice() == other.getPrice()) {
- return 1;
- }
- return 0;
- }
- }
Add Comment
Please, Sign In to add comment