In Java, the following are commonly used data structures provided by the Java Collections Framework:
- ArrayList: It is an implementation of the List interface and is backed by an array. It allows dynamic resizing of the array as elements are added or removed. Elements can be accessed using their index. ArrayList provides fast access to elements but slower insertion and deletion compared to LinkedList.
Example:
ArrayList<String> arrayList = new ArrayList<>(); arrayList.add("Apple"); arrayList.add("Banana"); arrayList.add("Orange"); System.out.println(arrayList.get(0)); // Output: Apple
- LinkedList: It is an implementation of the List interface and uses a doubly linked list to store elements. It provides efficient insertion and deletion operations but slower access to elements compared to ArrayList. LinkedList is preferred when frequent insertions and deletions are required.
Example:
LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("Apple"); linkedList.add("Banana"); linkedList.add("Orange"); System.out.println(linkedList.get(0)); // Output: Apple
- HashSet: It is an implementation of the Set interface and stores unique elements. It does not maintain any particular order of elements. HashSet provides constant-time performance for basic operations like add, remove, and contains.
Example:
HashSet<String> hashSet = new HashSet<>(); hashSet.add("Apple"); hashSet.add("Banana"); hashSet.add("Orange"); System.out.println(hashSet.contains("Apple")); // Output: true
- TreeSet: It is an implementation of the SortedSet interface and stores unique elements in a sorted order. TreeSet uses a binary search tree internally to store elements. It provides efficient operations for inserting, deleting, and retrieving elements in sorted order.
Example:
TreeSet<String> treeSet = new TreeSet<>(); treeSet.add("Apple"); treeSet.add("Banana"); treeSet.add("Orange"); System.out.println(treeSet.first()); // Output: Apple
- HashMap: It is an implementation of the Map interface and stores key-value pairs. HashMap allows null keys and null values. It provides constant-time performance for basic operations like put, get, and remove.
Example:
HashMap<String, Integer> hashMap = new HashMap<>(); hashMap.put("Apple", 1); hashMap.put("Banana", 2); hashMap.put("Orange", 3); System.out.println(hashMap.get("Apple")); // Output: 1
- TreeMap: It is an implementation of the SortedMap interface and stores key-value pairs in a sorted order of keys. TreeMap uses a binary search tree internally to store elements. It provides efficient operations for inserting, deleting, and retrieving elements in sorted order.
Example:
TreeMap<String, Integer> treeMap = new TreeMap<>(); treeMap.put("Apple", 1); treeMap.put("Banana", 2); treeMap.put("Orange", 3); System.out.println(treeMap.firstKey()); // Output: Apple
These data structures have different characteristics and are used in different scenarios based on the requirements of the application.