DEV Community

Cover image for Java Collections Framework
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

Java Collections Framework

Java Collections Framework (JCF) is a set of classes and interfaces that provide ready-made data structures to store and manipulate groups of objects efficiently.Java provides collection interfaces like List, Set, Map, and Queue, with ready-made classes such as ArrayList, HashSet, HashMap, and PriorityQueue, so you don’t have to write data-handling code from scratch.The Collection Framework improves productivity by making code more reusable, maintainable and faster to develop.
List
The List interface is part of the Java Collections Framework and represents an ordered collection of elements.You can access elements by their index, add duplicates, and maintain the insertion order.Since List is an interface, you cannot create a List object directly.Instead, you use a class that implements the List interface, such as:

  • ArrayList - like a resizable array with fast random access
  • LinkedList - like a train of cars you can easily attach or remove Note: Use List when you care about order, you may have duplicates, and want to access elements by index.  List vs Array  Common List Methods
  • add() --> adds an element to the end of the list.
import java.util.ArrayList;

public class Main {
  public static void main(String[] args) {
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars); //[Volvo, BMW, Ford, Mazda]
  }
}
Enter fullscreen mode Exit fullscreen mode
  • get()-->returns an element at the specified position.
System.out.println(cars.get(0));//volvo
Enter fullscreen mode Exit fullscreen mode
  • set()-->replaces the element at the specified position.
 cars.set(0, "Opel");
    System.out.println(cars);//[Opel, BMW, Ford, Mazda]
Enter fullscreen mode Exit fullscreen mode
  • remove--> remove an element at the specified position.
 cars.remove(0);
    System.out.println(cars);//[BMW, Ford, Mazda]
Enter fullscreen mode Exit fullscreen mode
  • size()-->returns the number of elements in the list.
import java.util.ArrayList;

public class Main { 
  public static void main(String[] args) { 
    ArrayList<String> cars = new ArrayList<String>();
    cars.add("Volvo");
    cars.add("BMW");
    cars.add("Ford");
    cars.add("Mazda");
    System.out.println(cars.size());//4
  } 
}
Enter fullscreen mode Exit fullscreen mode

References
https://www.w3schools.com/java/java_list.asp
https://www.geeksforgeeks.org/java/java-collection-tutorial/
https://www.geeksforgeeks.org/java/list-add-method-in-java-with-examples/
https://www.w3schools.com/java/java_ref_arraylist.asp

Top comments (0)