How to get a value inside an ArrayList java ?

Retrieve value from ArrayList in java
How to get Value from ArrayList

how to add new ArrayLists and ADD value to that particular ArrayList and how to RETRIEVE the data form that list.
    ArrayList<ArrayList<Integer>> arrayList=new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> newAL= new ArrayList<Integer>();
    arrayList.add(newAL);
    newAL.add(1);
    newAL.add(2);
    newAL.clear();      
    System.out.println(arrayList.get(0));
    //Changes persist in your arraylist
So after adding ArrayList you can manipulate newAL as ArrayList stores reference you don't need to fetch and set element from main arrayList.

To retrive data you can Iterate(Use ForEach Loop) over arrayList or you can do following
    Integer List0Item1=arrayList.get(0).get(1);//Get first element of list at 0
    arrayList.get(0).set(0, 10);//set 0th element of list at 0 as 10
    ArrayList<Integer> list10=arrayList.get(10);//get arraylist at position 10


For Example:-
main class
public class Test {
    public static void main (String [] args){
        Car thisCar= new Car ("Toyota", "$10000", "2003");  
        ArrayList<Car> car= new ArrayList<Car> ();
        car.add(thisCar); 
        processCar(car);
    } 

    public static void processCar(ArrayList<Car> car){
        for(Car c : car){
            System.out.println (c.getPrice());
        }
    }
}
car class
public class Car {
    private String vehicle;
    private String price;
    private String model;

    public Car(String vehicle, String price, String model){
        this.vehicle = vehicle;
        this.model = model;
        this.price = price;
    }

    public String getVehicle() {
        return vehicle;
    }

    public String getPrice() {
        return price;
    }

    public String getModel() {
        return model;
    }  
}

Comments

Popular posts from this blog

What is SIP or Session Initiation Protocol ?

How To Create An Object In Java ?

How do I declare and initialize an array in Java?