Header Ads

What is arayList | Methods of ArrayList | Java Porgramming



package collection;


import java.util.ArrayList;

import java.util.Iterator;


public class ArrayListDemo {


public static void main(String[] args) {

/*declaration

ArrayList myList=new ArrayList();

List myList1=new ArrayList();

*/

/* Storing only homogenous type data: For that use wrapper classes

 

ArrayList <Integer>mylist1=new ArrayList<Integer>(); //can store only integer

ArrayList <String>mylist2=new ArrayList<String>(); //can store only string

*/

//Adding element into arrayList

 

 

ArrayList myList=new ArrayList();

myList.add(2); //it will store as primitive wrapper class

myList.add("A");

myList.add(5);

myList.add(true);

myList.add(null);

myList.add(null);

myList.add("rajat");

//size of arraylist

int size=myList.size(); 

System.out.println("size of array list"+ size);

// print arraylist

System.out.println("arraylist is"+" " + myList);

//remove any element from arraylist

myList.remove(6);

// print arraylist after remove the 7th element

System.out.println("arraylist is"+ " " +  myList);

//insertion element in the arraylist

//by add element means , element will add at the end of arraylist

myList.add(2,"rajat");

System.out.println("arraylist is"+ " " +  myList);

//modify any element 

 

myList.set(0, "bhatti");

 

System.out.println("Modified arraylist is"+ " " +  myList);

 

//accesing specific element

 

// System.out.println(myList.get(2));

 

// //reading all the element

//  

// //approach 1: using normal loop

// for(int i=0;i<myList.size();i++)

// {

// System.out.println(myList.get(i));

// }

//  

// //approach 2: using for each loop or enhance loop

// for( Object x:myList) // as myList is a object type 

// {

// System.out.println(x);

//  

// }

//  

// //approach 3: using iterator 

//  

// Iterator it=myList.iterator(); // iterator is a method which is already defined in the arraylist

//

// while(it.hasNext()) //hasNext check element is present or not and return true or false

// {

// System.out.println(it.next()); //next method will print the next element

// }

 

//checking arrayList is empty or not

boolean empty= myList.isEmpty();

System.out.println(empty);

// //to clear the list

// myList.clear();

// System.out.println("list is "+ myList);

//How to remove multiple element at a time

// first create a another arraylist and add all those element which you want to remove from arraylist1

//and then pass second array list as the argument in removeAll() method

//Using this, if duplicate element are there then all duplicate element will be removed

ArrayList myList2=new ArrayList();

myList2.add("bhatti");

myList2.add(true);

myList2.add(5);

myList.removeAll(myList2);

System.out.println(myList);

 

 


}


}


No comments

Powered by Blogger.