- List maintains elements in Particular Sequence.
- Two types of List 1.ArrayList and 2.LinkedList
- ArrayList is faster while accessing elements but slower while Insertion and Deletion
- LinkedList is slow in random access but faster during insertion and deletion
Operations in ArrayList
class Fruits
{
String Name = "Fruit";
}
class Apple extends Fruits
{
public Apple()
{
Name = "Apple";
}
}
class Orange extends Fruits
{
public Orange()
{
Name = "Orange";
}
}
class Mango extends Fruits
{
public Mango()
{
Name = "Mango";
}
}
Adding Element – List.add()
List<Fruits> arrFruits = new ArrayList<Fruits>();
Fruits objApple = new Apple();
Fruits objMango = new Mango();
arrFruits.add(objApple);
arrFruits.add(objMango);
Removing Element – List.remove()
arrFruits.remove(objApple);
Removing by Index – List.remove()
arrFruits.remove(1);
Index of Element – List.indexOf()
arrFruits.indexOf(objMango);
Index of Element – List.indexOf()
arrFruits.indexOf(objMango);
SubList – List.subList(StartPOS, EndPOS)
List<Fruits> arrNewFruits = arrFruits.subList(0,2);
containsAll – NewList.containsAll(OrgList)
arrNewFruits.containsAll(arrFruits);
set Value at Index
arrNewFruits.set(1, new Orange());
removeAll
arrFruits.removeAll(arrFruits);
addAll
arrFruits.addAll(arrNewFruits);
retainAll – set Intersection Operation
retainAll performs set Interscetion Operation by taking Two ArrayList. It Retains Boolean true if intersection finds element false otherwise.
List<Integer> arrNums1 = new ArrayList<Integer>();
arrNums1.add(1);
arrNums1.add(2);
arrNums1.add(3);
List<Integer> arrNums2 = new ArrayList<Integer>();
arrNums2.add(1);
System.out.println(arrNums1.retainAll(arrNums2));
System.out.println(arrNums1);