Saturday, 16 August 2014

How to add instance of a class to list and then retrieve it

Suppose we have a class Car with 2 properties Car model and car name.
We want to add instances of this class to a list so that later we can retrieve it.

See :

How to sort an Array List without using Comparator or sort method
Overriding/method Overriding In java
Difference between Application Server and Web server 

Car.java
package test;

public class Car {

private String carName;
private String carModel;
public Car()
{

}
public String getCarName() {
return carName;
}
public void setCarName(String carName) {
this.carName = carName;
}
public String getCarModel() {
return carModel;
}
public void setCarModel(String carModel) {
this.carModel = carModel;
}


}

Difference between LinkedList and ArrayList
Difference between Arrays.sort() and collections.sort() 
How to reverse a string in java
----------------------------------------------

main.java

package test;

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class MainS {

public static void main(String[] args) {
Car car1= new Car();
car1.setCarName("skoda");
car1.setCarModel("2005");
Car car2 = new Car();
car2.setCarName("limo");
car2.setCarModel("2006");
List carList= new ArrayList<Car>();
carList.add(car1);
carList.add(0, car2);
ListIterator l =  carList.listIterator();
while (l.hasNext())
{
Car c=(Car) l.next();
System.out.println(c.getCarModel());
System.out.println(c.getCarName());
}
}
}

Exception Handling in Java
Static varibale,static class,Static method

2 comments: