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);
Â
Â
}
}
Post a Comment