ArrayList of Objects in Java (Car Class)
ArrayList of Objects in Java (Car Class)
In this entry we are going to write a Java program that creates an ArrayList of Objects of type Car.
the program prompts for the car data through the keyboard and stores it in the array. It will then use the
ArrayList to display the following on screen:
- All the cars introduced.
- All cars of a certain brand.
- All cars with less than a certain number of kilometers.
- The car with the highest number of kilometers.
- All cars sorted by number of kilometers from least to most.
First we create the Car class:
//Car Class
public class Car {
private String enrollment;
private String brand;
private String model;
private int Km;
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
data:text/html;charset=utf-8,<div class="fauxcolumn-outer fauxcolumn-left-outer" style="position: absolute;… 1/4
March 29, 2015 Java Programming: ArrayList of Objects in Java
Registration:
sb.append(matricula);
Brand:
sb.append(brand);
Model:
sb.append(model);
Km:
sb.append(Km);
return sb.toString();
}
}
//main class
public class Basic1 {
Km = sc.nextInt();
sc.nextLine(); //clear the input
aux = new Car(); //A Car object is created and
its reference is assigned to aux
values are assigned to the attributes of the new
object
aux.setRegistration(matricula);
aux.setBrand(brand);
aux.setModel(model);
aux.setKm(Km);
We can graphically represent the contents of the ArrayList as the objects are introduced:
Method that shows the cars sorted by number of Km from lowest to highest
public static void showSortedByKm() {
int i, j;
Car aux;
for(i = 0; i < cars.size() - 1; i++)
for(j=0;j<cars.size()-i-1;j++)
if(cars.get(j+1).getKm() < cars.get(j).getKm()){
aux = cars.get(j + 1);
cars.set(j+1, cars.get(j));
cars.set(j, aux);
}
showCars();
}
} // end of the main class
data:text/html;charset=utf-8,%3Cdiv%20class%3D%22fauxcolumn-outer%20fauxcolumn-left-outer%22%20style%3D%22position%3A%20absolute%3B%… 4/4