synchronized, unmodifiable and checked Collections explained

In Java, the synchronized, unmodifiable, and checked collections are special types of collections that provide additional thread safety, immutability, or type safety.

The synchronized collections are thread-safe collections that can be used in a multithreaded environment. They provide methods that are synchronized to prevent multiple threads from accessing the collection concurrently, which can lead to race conditions or other concurrency issues. The synchronized collections include the SynchronizedList, SynchronizedSet, and SynchronizedMap classes.

Here is an example of how to use the SynchronizedList class:

import java.util.Collections;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> words = Collections.synchronizedList(new ArrayList<>());

    // Add elements to the list
    words.add("apple");
    words.add("banana");
    words.add("cherry");

    // Iterate over the list
    synchronized (words) {
      for (String word : words) {
        System.out.println(word);
      }
    }
  }
}

The unmodifiable collections are immutable collections that cannot be modified after they are created. They provide a read-only view of a collection and throw an exception if you try to modify the collection in any way. The unmodifiable collections include the UnmodifiableList, UnmodifiableSet, and UnmodifiableMap classes.

Here is an example of how to use the UnmodifiableList class:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    List<String> words = new ArrayList<>();
    words.add("apple");
    words.add("banana");
    words.add("cherry");

    // Create an unmodifiable list
    List<String> unmodifiableWords = Collections.unmodifiableList(words);

    // Try to modify the list
    unmodifiableWords.add("date");  // throws UnsupportedOperationException
  }
}

The checked collections are type-safe collections that check the type of the elements added to the collection at runtime. They provide a way to ensure that a collection only contains elements of a specific type and throw a ClassCastException if an invalid element is added. The checked collections include the CheckedList, CheckedSet, and CheckedMap classes.

Here is an example of how to use the CheckedList class:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
  public static void main(String[] args) {
    // Create a checked list that only accepts strings
    List<String> words = Collections.checkedList(new ArrayList<>(), String.class);

    // Add elements to the list
    words.add("apple");
    words.add("banana");
    words.add("cherry");

    // Try to add an invalid element
    words.add(1);  // throws Class