-5

I've created a class Car, with these attributes and methods. I've used a list to store several objects.

package com.company;
import java.util.ArrayList;
import java.util.Collections;

class Car implements Comparable<Car> {
    private String manufacturer;
    private int speed;
    private double price;
    private int year; // manufacture year

    public Car(String manufacturer, int speed, double price, int year) {
        this.manufacturer = manufacturer;
        this.speed = speed;
        this.price = price;
        this.year = year;
    }

    public String getManufacturer() {
        return manufacturer;
    }

    public int getSpeed() {
        return speed;
    }

    public double getPrice() {
        return price;
    }

    public int getYear() {
        return year;
    }

    public String toString() {
        return this.manufacturer + ", speed: " + this.speed + "km/h, price: " + this.price + " USD, year: " + this.year;
    }


    public int compareTo(Car c) {
        if (this.price == c.price)
            return 0;
        else if(this.price > c.price)
            return 1;
        else
            return -1;

    }
}

public class Solution {
    public static void main(String[] args) {
        List<Car> cars = new ArrayList<Car>();
        cars.add(new Car("Audi", 280, 35300, 2018));
        cars.add(new Car("Mercedes-Benz", 155, 80000, 2009));
        cars.add(new Car("Toyota", 155, 18750, 2011));
        cars.add(new Car ("Fiat", 140, 22500, 2000));
        cars.add(new Car ("Land Rover", 209, 90900, 2014));
         for (Car iterator: cars) {
            System.out.println(iterator);
        }

         Collections.sort(cars);
         for (Car iterator: cars) {
             System.out.println(iterator.getPrice());
         }
    }
}

After using Comparable interface, I would like to access the first element of the sorted list, because I want to obtain the cheapest car, for example. How could I do that?

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35

3 Answers3

5

For ArrayList you can access the first element by this way:

cars.get(0);

For LinkedList:

cars.getFirst();
roddar92
  • 353
  • 1
  • 4
1
cars.get(0);

But do not forget that you could have many thay one cars with the minimum price:

Collections.sort(cars);

double minPrice = cars.get(0).price;

for (Car car : cars) {
    if (Double.compare(car.gePrice(), minPrice) != 0)
        break;
    
    System.out.println(car);
}
Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35
0

You can use below code to achieve that.

cars.get(0);

Hasindu Dahanayake
  • 1,344
  • 2
  • 14
  • 37