Brother Jie teaches you one hundred questions in the interview series: java collection

Article directory


Collections are something we often use in Java. Once we are familiar with collections, we will become familiar with Java. When the interviewer involves questions about Java collections in the Java interview, they usually involve the concepts, types, common operations, performance, etc. of collections.

1. What are Java collections? Please briefly introduce the collection framework.

Answer:
Java collection is a collection of classes and interfaces used to store, manage and operate a set of objects. The collection framework provides many different types of collection implementations to meet different needs, including lists, sets, maps, etc. The collection framework is located under the java.util package. It provides a set of interfaces and classes for storing and operating objects, making data processing more convenient and efficient.

2. What are the main types of Java collection framework?

Answer:
Java collection framework is mainly divided into the following three types:

  • List: An ordered collection, allowing duplicate elements. Common implementation classes include ArrayList, LinkedList, etc.
  • Set (set): An unordered set, no duplicate elements are allowed. Common implementation classes include HashSet, TreeSet, etc.
  • Map: Key-value pair mapping, each key can only correspond to one value. Common implementation classes include HashMap, TreeMap, etc.

3. What is an iterator? What does it do?

Answer:
Iterator is an interface in the collection framework, used to traverse the elements in the collection. It provides a unified way to access the elements in a collection without caring about the specific implementation of the collection. Through iterators, you can access the elements in a collection one by one in sequence without exposing the internal structure of the collection.

Code example:

List<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String fruit = iterator.next();
    System.out.println(fruit);
}

4. What is the difference between ArrayList and LinkedList? When do they apply?

answer:

  • ArrayList: Based on dynamic array implementation, it is suitable for scenarios with many random access and read operations. Inserting and deleting elements requires moving the element position, so the efficiency is relatively low during frequent insertion and deletion operations.
  • LinkedList: Based on a doubly linked list, it is suitable for frequent insertion and deletion operations, because inserting and deleting elements in a linked list only requires modifying the pointers of adjacent nodes, which is more efficient. . But random access is slower.

Which collection to choose depends on the specific usage scenario and frequency of operations.

5. What is the difference between HashMap and HashTable?

answer:

  • HashMap: allows null keys and null values, is not thread-safe (non-synchronized), and performs better in most cases.
  • HashTable: does not allow the use of null keys and null values, is thread-safe (synchronous), and has relatively poor performance.

Due to the large synchronization performance overhead of HashTable, HashMap is generally used in a single-threaded environment, and ConcurrentHashMap can be used to replace HashTable in a multi-threaded environment.

6. What is ConcurrentModificationException? How is it caused and how can it be avoided?

Answer:
ConcurrentModificationException is an exception that will be thrown when using an iterator to traverse a collection, if the structure of the collection is modified during the traversal process (such as adding or deleting elements) . This is because the iterator uses a counter to detect whether the collection has been modified during the iteration process.

A common way to avoid this exception is to use the iterator's delete method to delete elements, rather than using the delete operation directly on the collection.

Code example:

List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);

Iterator<Integer> iterator = numbers.iterator();
while (iterator.hasNext()) {
    Integer number = iterator.next();
    if (number == 2) {
        iterator.remove(); // 正确的删除方式,不会抛出ConcurrentModificationException
    }
}

7. What are equals() and hashCode() methods? Why are they important in the collection?

answer:

  • equals(): is a method defined in the Object class, used to compare whether two objects are equal. In sets, such as HashSet and HashMap, it is used to determine whether two elements are equal.
  • hashCode(): is also a method defined in the Object class and returns the hash code value of the object. In a collection, such as HashMap, it is used to determine the storage location of objects in the collection.

In containers that need to be searched and stored based on the equality of elements, such as HashSet and HashMap in the collection framework, it is very important to correctly implement the equals() and hashCode() methods to ensure the consistency and correctness of the elements.

8. What are Comparable and Comparator interfaces?

answer:

  • Comparable interface: Defines the natural ordering method on objects so that objects can be compared with other objects. Classes that implement the Comparable interface can use the compareTo() method to implement comparison logic.
  • Comparator interface: is a customized sorting interface for comparing two objects, which can implement a variety of different comparison logics without modifying the object class.

Achieved

Classes with the Comparable interface can directly use Collections.sort() for sorting, while using the Comparator interface can provide customized comparison logic where needed.

Code example:

class Person implements Comparable<Person> {
    private String name;
    private int age;

    // Constructors, getters, setters

    @Override
    public int compareTo(Person otherPerson) {
        return Integer.compare(this.age, otherPerson.age);
    }
}

List<Person> people = new ArrayList<>();
// Add people to the list
Collections.sort(people); // 使用自然排序

// 使用Comparator进行定制排序
Comparator<Person> ageComparator = Comparator.comparingInt(Person::getAge);
Collections.sort(people, ageComparator);

9. What are Synchronized Collections? In what situations are they used?

Answer:
Synchronized collection refers to a collection class that provides thread-safe operations for multi-threaded environments. In the case of concurrent access, ordinary collection classes may cause thread safety issues, so Java provides methods such as Collections.synchronizedList, Collections.synchronizedSet, etc. to return synchronized versions of collections.

Code example:

List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());
Set<Integer> synchronizedSet = Collections.synchronizedSet(new HashSet<>());

// 在多线程环境中使用同步集合

10. What are Concurrent Collections? What is their function?

Answer:
Concurrent collection refers to a collection class specially designed for multi-threaded concurrent operations, which can provide higher concurrency performance. The java.util.concurrent package provides many concurrent collections, such as ConcurrentHashMap, ConcurrentSkipListMap, ConcurrentLinkedQueue, etc.

These collections use different concurrency control strategies to allow multiple threads to access and modify the collection simultaneously without requiring explicit synchronization control. This is very useful for high-concurrency application scenarios.

Code example:

ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("one", 1);
concurrentMap.put("two", 2);

// 在多线程环境中安全地进行操作

11. What are Fail-Fast and Fail-Safe iterators?

answer:

  • Fail-Fast iterator: When the collection is modified (added, deleted elements) during the iteration process, ConcurrentModificationException will be thrown immediately to avoid potential problems in a concurrent environment. The problem. This iterator is mainly used to detect illegal modifications to a collection during the iteration process.

  • Fail-Safe iterator: The iterator will copy the data of the original collection, allowing the collection to be modified during the iteration process, but will not affect the ongoing iteration process. This kind of iterator is suitable for situations where the collection needs to be allowed to be modified during the iteration process, such as in a concurrent environment.

CopyOnWriteArrayList and CopyOnWriteArraySet in the Java collection framework are examples of Fail-Safe collections.

12. What are the main interfaces in the Java collection framework?

Answer:
The main collection interfaces include:

  • Collection: Represents a group of objects, including List and Set.
  • List: An ordered collection that can contain repeated elements. Common implementations include ArrayList, LinkedList, etc.
  • Set: An unordered set that does not allow repeated elements. Common implementations include HashSet, TreeSet, etc.
  • Map: Key-value pair mapping. Each key can only correspond to one value. Common implementations include HashMap, TreeMap, etc.

13. What is WeakHashMap?

Answer:
WeakHashMap is a special Map implementation provided in the java.util package, and its key is a weak reference (WeakReference). This means that when a key is no longer referenced by other parts of the program, it can be reclaimed by the garbage collector, even if the key is in a WeakHashMap.

WeakHashMap is often used in scenarios where you need to associate an object with relevant additional information, but do not want to hinder the garbage collection process. Typical applications are caching and resource management.

Code example:

WeakHashMap<Key, Value> weakMap = new WeakHashMap<>();
Key key = new Key(); // 仅被weakMap引用
Value value = new Value(); // 与key相关的值
weakMap.put(key, value);

// 当key不再被其他部分引用,垃圾回收时,weakMap中的对应条目会被移除

14. What is the agreement between HashCode and Equals?

Answer:
The hashCode and equals methods have some conventions in the collection framework:

  • If two objects are equal via the equals method, their hashCode values ​​must be equal.
  • If the hashCode values ​​of two objects are equal, they are not necessarily equal through the equals method, but in collections such as HashMap, equal hash codes will increase the length of the linked list and affect performance, so it is best to maintain consistency.

In order to comply with these conventions, when you override the equals method in a custom class, you should also override the hashCode method to ensure the correct behavior and performance of objects in the collection.

Code example:

class Student {
    private int id;
    private String name;

    // Constructors, getters, setters

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return id == student.id && Objects.equals(name, student.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name);
    }
}

15. What is IdentityHashMap?

Answer:
IdentityHashMap is a special Map implementation that uses the referenced identity (memory address) instead of the equals method when comparing keys and values ​​for equality. This allows it to distinguish between cases where different references point to the same content.

IdentityHashMap is suitable for scenarios where key-value pairs need to be stored based on the identity of the object reference rather than the content.

Code example:

IdentityHashMap<String, Integer> identityMap = new IdentityHashMap<>();
String key1 = new String("key");
String key2 = new String("key");
identityMap.put(key1, 1);
identityMap.put(key2, 2);

System.out.println(identityMap.size()); // 输出 2,因为两个键在引用上不同

16. What are EnumSet and EnumMap?

answer:

  • EnumSet: is a collection class in the java.util package specially designed for enumeration types. It is implemented based on bit vectors and is suitable for fast set operations of enumeration types and is very efficient.
  • EnumMap: is also a Map implementation specifically designed for enumeration types in the java.util package. Its key must be an enumeration value of the same enumeration class, providing very efficient enumeration key-value pair storage and search operations.

These two classes are very useful when dealing with enumeration type data because they are specially optimized for enumeration types.

Code example:

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

EnumSet<Day> weekdays = EnumSet.range(Day.MONDAY, Day.FRIDAY);
EnumMap<Day, String> activities = new EnumMap<>(Day.class);
activities.put(Day.MONDAY, "Working");
activities.put(Day.FRIDAY, "Partying");

17. What are the utility methods of Collections class?

Answer:
The java.util.Collections class provides a series of static utility methods for operating collections. These methods include sorting, finding, replacing, etc., and they can be used in a variety of different collection implementations.

Code example:

List<Integer> numbers = new ArrayList<>();
numbers.add(5);
numbers.add(2);
numbers.add(8);

Collections.sort(numbers); // 对列表进行排序

int index = Collections.binarySearch(numbers, 5); // 二分查找

18. What are Unmodifiable Views of Collections class?

Answer:
The Collections.unmodifiableXXX() method can return an unmodifiable view, which is used to encapsulate the existing collection so that it does not allow modification operations. This is useful when you need to pass a collection to other parts, but don't want those parts to be able to modify the collection.

Code example:

List<String> originalList = new ArrayList<>();
originalList.add("Apple");
originalList.add("Banana");

List<String> unmodifiableList = Collections.unmodifiableList(originalList);

// 试图修改unmodifiableList会引发UnsupportedOperationException

19. What are the synchronized methods of Collections class?

Answer:
The java.util.Collections class provides some static methods for returning thread-safe collections. These methods are useful when you need to ensure safe access to collections in a multi-threaded environment. Common synchronization methods include Collections.synchronizedList, Collections.synchronizedSet and Collections.synchronizedMap, etc.

Code example:

List<String> synchronizedList = Collections.synchronizedList(new ArrayList<>());
Set<Integer> synchronizedSet = Collections.synchronizedSet(new HashSet<>());
Map<String, Integer> synchronizedMap = Collections.synchronizedMap(new HashMap<>());

20. What is ListIterator?

Answer:
ListIterator is a special iterator provided by the List interface. In addition to the functions of ordinary iterators, it can also insert and delete elements into the list during the iteration process. . ListIterator allows bidirectional traversal (forward and backward) and provides many more operations.

Code example:

List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

ListIterator<String> iterator = names.listIterator();
while (iterator.hasNext()) {
    String name = iterator.next();
    if (name.equals("Bob")) {
        iterator.add("David"); // 在Bob之后插入David
    }
}

21. What are the reverse() and shuffle() methods of Collections class?

Answer:
The Collections.reverse() method is used to reverse the sorting of elements in a List. The Collections.shuffle() method is used to randomly shuffle the order of elements in a List. These two methods are very useful when dealing with the order of elements in a list.

Code example:

List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);

Collections.reverse(numbers); // 反转列表

Collections.shuffle(numbers); // 随机打乱列表

22. What is PriorityQueue?

Answer:
PriorityQueue is a queue implementation based on the priority heap (heap), which can be sorted according to the priority of elements. By default, PriorityQueue sorts in natural order, but you can also specify how elements are sorted by providing a custom Comparator.

Code example:

PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
priorityQueue.add(5);
priorityQueue.add(2);
priorityQueue.add(8);

int highestPriority = priorityQueue.poll(); // 弹出具有最高优先级的元素

23. What is BitSet?

Answer:
BitSet is a collection class used to store bit information. Each element of it has only two possible values: 0 and 1. BitSet is often used to handle bit operations and flag bit operations, such as in bitmap indexing, compression algorithms, etc.

Code example:

BitSet bitSet = new BitSet(8); // 创建一个有8位的BitSet

bitSet.set(2); // 设置第2位为1
bitSet.set(5); // 设置第5位为1

boolean isSet = bitSet.get(2); // 获取第2位的值(true)

24. What is the asList() method of Arrays class?

Answer:
The Arrays.asList() method is a utility method provided by the java.util.Arrays class for converting an array into a List. Note that the List returned by this method is of fixed size and does not support addition and deletion operations, but elements can be modified using the set() method.

Code example:

String[] array = {"Apple", "Banana", "Orange"};
List<String> list = Arrays.asList(array);

list.set(1, "Pear"); // 修改数组中的元素

25. What is LinkedHashMap?

Answer:
LinkedHashMap is a class in the java.util package that implements the Map interface. It inherits from HashMap, but additionally maintains the insertion order of key-value pairs. This means that when you iterate over a LinkedHashMap, the key-value pairs are in the same order as they were inserted.

LinkedHashMap is suitable for scenarios where the insertion order of elements needs to be maintained, and elements can also be traversed through access sequence mode.

Code example:

LinkedHashMap<String, Integer> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("one", 1);
linkedHashMap.put("two", 2);
linkedHashMap.put("three", 3);

// 遍历顺序与插入顺序一致
for (Map.Entry<String, Integer> entry : linkedHashMap.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}

26. What is Stream API?

Answer:
The Stream API is a powerful feature introduced in Java 8. It provides a functional programming method for processing collection data. Stream allows you to perform a series of operations on the elements in the collection, such as filtering, mapping, sorting, reduction, etc., in a functional style.

The Stream API can make code more concise and clear, and in some cases can provide more efficient parallel processing.

Code example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

int sum = numbers.stream()
                .filter(n -> n % 2 == 0)
                .mapToInt(Integer::intValue)
                .sum();

27. What is a Lambda expression? What is its role in collection operations?

Answer:
Lambda expression is a lightweight functional programming feature introduced in Java 8 that allows you to pass anonymous functions in a more compact way. In set operations, Lambda expressions can be used to transfer the logic of operations, such as filtering, mapping, sorting, etc., making the code more concise and readable.

Lambda expressions can help you shift the focus of operations from "how to implement" to "what to implement", thereby improving the readability and maintainability of your code.

Code example:

List<String> names = Arrays.asList("Alice", "Bob", "Charlie");

names.stream()
     .filter(name -> name.length() <= 4)
     .forEach(System.out::println);

28. What is the Collectors class?

Answer:
java.util.stream.Collectors is a tool class in the Stream API, which provides a set of static methods for collecting elements in a Stream into a collection or in other data structures. It is very useful in the final operation of Stream and can be used for operations such as summarization, grouping, and partitioning.

The methods of the Collectors class can help you collect Stream results in a more concise way.

Code example:

List<Person> people = // ... 获得一组人员数据

Map<String, List<Person>> peopleByCity = people.stream()
    .collect(Collectors.groupingBy(Person::getCity));

29. What is parallel Stream?

Answer:
Parallel Stream refers to a way of processing elements in a Stream in multiple threads at the same time. The Stream API introduced in Java 8 allows you to convert a normal Stream into a parallel Stream by calling the parallel() method. This can improve processing efficiency when processing large amounts of data.

However, be aware that when using parallel Streams, thread safety issues need to be considered, as well as possible performance overhead in some cases.

Code example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

int sum = numbers.parallelStream()
                .filter(n -> n % 2 == 0)
                .mapToInt(Integer::intValue)
                .sum();

30. What is ConcurrentSkipListMap?

Answer:
ConcurrentSkipListMap is a concurrent mapping implementation provided in the java.util.concurrent package. It is based on the Skip List data structure. ConcurrentSkipListMap provides high concurrency performance and is suitable for concurrent access in a multi-threaded environment.

A skip list is an ordered data structure similar to a balanced tree, but with better concurrency performance.

Code example:

ConcurrentSkipListMap<String, Integer> skipListMap = new ConcurrentSkipListMap<>();
skipListMap.put("one", 1);
skipListMap.put("two", 2);

int value = skipListMap.get("two");

31. What are EnumSet and EnumMap?

answer:

  • EnumSet: is an efficient collection class designed for enumeration types in the java.util package. It is based on bit vector implementation and is suitable for storing and operating elements of enumeration types. . Because enumeration values ​​are limited, using bit vectors can provide efficient storage and access.
  • EnumMap: is an efficient mapping class designed for enumeration types in the java.util package. Its keys must be enumeration values ​​of the same enumeration class. EnumMap uses arrays internally to store mapped key-value pairs, so it has efficient access performance.

Both classes are specific optimizations for enumeration type data and provide efficient storage and operation.

Code example:

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);

EnumMap<Day, String> activities = new EnumMap<>(Day.class);
activities.put(Day.MONDAY, "Working");
activities.put(Day.FRIDAY, "Partying");

32. What are WeakReference, SoftReference and PhantomReference?

Answer:
These are reference types in Java that are used to control garbage collection of objects in memory management:

  • WeakReference (weak reference): Weak reference objects will only be recycled when there is insufficient memory during garbage collection. Often used to build caches, objects in the cache can be garbage collected when they are no longer strongly referenced.
  • SoftReference: Soft reference objects will be recycled when memory is insufficient. Used to implement caching, but more "persistent" than weak references, which is beneficial to utilizing remaining memory.
  • PhantomReference: A phantom reference is used to get notified before an object is garbage collected. Virtual reference objects may be garbage collected at any time.

These reference types are very useful in some special scenarios, such as memory-sensitive caching and resource release.

33. What are the natural sorting and customized sorting of the Comparator interface?

Answer:
The Comparator interface defines a comparator for sorting objects. It has two sorting methods:

  • Natural Ordering: For classes that implement the Comparable interface, they can be sorted in natural order. For example, integers and strings already implement the Comparable interface, so they can be sorted using natural ordering.
  • Custom Ordering: When you need to sort classes that do not implement the Comparable interface, you can specify the sorting rules by providing a custom Comparator. This way you can define multiple sorting methods without modifying the class itself.

Code example:

class Student {
    private String name;
    private int age;

    // Constructors, getters, setters
}

List<Student> students = // ... 获得一组学生数据

// 自然排序
Collections.sort(students);

// 定制排序
Comparator<Student> ageComparator = Comparator.comparingInt(Student::getAge);
Collections.sort(students, ageComparator);

34. What is IdentityHashMap?

Answer:
IdentityHashMap is a class provided in the java.util package that implements the Map interface. It uses the referenced identity (memory address) instead of the equals method to determine the equality of keys. sex. This means that two keys are considered equal only if they refer to the same object.

This is useful in certain situations, such as where a key-value store needs to be based exactly on the object's identity.

Code example:

IdentityHashMap<String, Integer> identityMap = new IdentityHashMap<>();
String key1 = new String("key");
String key2 = new String("key");
identityMap.put(key1, 1);

// key2不等于key1,所以不会被视为相等的键
identityMap.get(key2); // 输出null

35. What is the checkedXXX method of Collections class?

Answer:
The java.util.Collections class provides a series of methods for creating typed-safe collections, which are called checkedXXX methods. These methods can help you ensure that the type of element you add to the collection is

correct, thereby avoiding type conversion errors at runtime.

Code example:

List<String> stringList = new ArrayList<>();
List checkedList = Collections.checkedList(stringList, String.class);

// 现在只能添加String类型的元素到checkedList

36. What are CopyOnWriteArrayList and CopyOnWriteArraySet?

Answer:
CopyOnWriteArrayList and CopyOnWriteArraySet are both concurrent collections and belong to the java.util.concurrent package. They achieve highly concurrent read operations by using a special copy-on-write (Copy-On-Write) strategy.

  • CopyOnWriteArrayList: is a thread-safe List implementation, suitable for scenarios where there is more reading and less writing. During modification operations (adding, deleting elements), it copies the original array and modifies it to ensure thread safety for read operations.
  • CopyOnWriteArraySet: is a thread-safe Set implementation, which is based on CopyOnWriteArrayList implementation and has similar characteristics.

These collections provide an efficient solution for situations where there are many reads and few writes.

Code example:

CopyOnWriteArrayList<String> copyOnWriteList = new CopyOnWriteArrayList<>();
CopyOnWriteArraySet<Integer> copyOnWriteSet = new CopyOnWriteArraySet<>();

// 在多线程环境中使用copyOnWriteList和copyOnWriteSet

37. What is the disjoint() method of Collections class?

Answer:
The Collections.disjoint() method is used to check whether two collections have no common elements. If the two sets have no intersection, that is, there are no common elements between them, this method returns true, otherwise it returns false.

Code example:

List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);

boolean noCommonElements = Collections.disjoint(list1, list2);
System.out.println(noCommonElements); // 输出 true

38. What is the reverseOrder() method of Collections class?

Answer:
The Collections.reverseOrder() method returns a reverse order comparator, which is used to sort the elements in reverse order. Usually used together with the Collections.sort() method to sort the elements in the collection in reverse order.

Code example:

List<Integer> numbers = Arrays.asList(5, 2, 8, 1);

Collections.sort(numbers, Collections.reverseOrder());

39. What is the singletonXXX() method of Collections class?

Answer:
The Collections.singletonXXX() method is used to create an unmodifiable collection containing only one element. This kind of collection is more compact internally and is suitable for scenarios that only contain a single element.

Code example:

Set<String> singletonSet = Collections.singleton("Hello");

List<Integer> singletonList = Collections.singletonList(42);

40. What is the emptyXXX() method of Collections class?

Answer:
The Collections.emptyXXX() method is used to create an empty unmodifiable collection, such as emptyList(), emptySet() and emptyMap(). These collections are useful when there is no need to store elements, to avoid creating unnecessary instances.

Code example:

List<String> emptyList = Collections.emptyList();
Set<Integer> emptySet = Collections.emptySet();
Map<String, Integer> emptyMap = Collections.emptyMap();

41. What is ConcurrentHashMap?

Answer:
ConcurrentHashMap is a concurrent hash map implementation provided in the java.util.concurrent package, which allows multiple threads to read and write the map simultaneously without throwing Concurrency conflicts. ConcurrentHashMap is designed to perform well in high concurrency situations.

It implements concurrent write operations by dividing the map into segments, each segment equivalent to a small hash table. Different segments can be operated simultaneously by different threads, thereby reducing lock contention.

Code example:

ConcurrentHashMap<String, Integer> concurrentMap = new ConcurrentHashMap<>();
concurrentMap.put("one", 1);
concurrentMap.put("two", 2);

int value = concurrentMap.get("one");

42. What is a Spliterator?

Answer:
Spliterator is an interface introduced in Java 8 for traversing and splitting a sequence of elements. It is the abbreviation of "Split Iterator". Spliterator can be used to support parallel iterative operations, splitting the data source into multiple parts for parallel processing by multiple threads.

Spliterator is widely used to support the new Stream API and parallel streams.

Code example:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);

Spliterator<Integer> spliterator = numbers.spliterator();

// 并行迭代
spliterator.forEachRemaining(System.out::println);

43. What are the characteristics of the Set interface?

Answer:
The Set interface is an interface in the java.util package, which means that a set containing duplicate elements is not allowed. Set's key features include:

  • Duplicate elements are not allowed: elements in the set are unique and cannot be repeated.
  • Unordered: Sets generally do not guarantee a specific order of elements. Actual order may change over time.
  • No index: Set does not support accessing elements by index because it does not define a specific order.

Commonly used Set implementations include HashSet, LinkedHashSet and TreeSet.

44. What is NavigableSet interface?

Answer:
The NavigableSet interface is a sub-interface in the java.util package that extends the SortedSet interface. It provides a series of methods for navigating and searching elements. The main features of NavigableSet include:

  • Methods are provided for searching for the smallest and largest elements.
  • Provides methods for searching for a given element, or for elements greater or smaller than a given element.
  • Can get the previous and next element.

TreeSet is a common implementation of the NavigableSet interface.

45. What is BlockingQueue?

Answer:
BlockingQueue is an interface in the java.util.concurrent package. It is a queue that supports thread-safe producer-consumer mode. BlockingQueue provides blocking operations. When the queue is empty or full, read and write operations will be blocked until the conditions are met.

BlockingQueue is useful in multi-threaded applications to implement concurrent producer and consumer threads.

Code example:

BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>();

// 生产者线程
blockingQueue.put(1);

// 消费者线程
int value = blockingQueue.take();

46. ​​What is the Deque interface?

Answer:
The Deque interface (abbreviation of Double Ended Queue) is an interface in the java.util package and represents a two-way queue. Deque allows you to insert and delete elements from both ends of the queue, and can be used as a hybrid of queue and stack.

Deque provides a series of methods for operating on the head and tail of the queue, such as addFirst(), addLast(), removeFirst(), removeLast(), etc.

Code example:

Deque<String> deque = new LinkedList<>();
deque.addLast("Alice");
deque.addLast("Bob");
deque.addFirst("Charlie");

String first = deque.removeFirst(); // 输出 Charlie

47. What is the BlockingDeque interface?

Answer:
The BlockingDeque interface is an interface in the java.util.concurrent package and an extension of Deque. It combines the bidirectional queue feature of Deque and the blocking feature of BlockingQueue. BlockingDeque allows insertion and removal of elements from both ends of the queue and provides blocking operations when the queue is empty or full.

BlockingDeque is suitable for bidirectional queue scenarios that require high concurrency, such as the producer-consumer model.

48. What are EnumMap and EnumSet?

answer:

  • EnumMap: EnumMap is a class in the java.util package that implements the Map interface and is specifically used when enumeration types are used as keys. Its keys must come from the same enum class, which makes it more efficient with enum keys.
  • EnumSet: EnumSet is a class in the java.util package that implements the Set interface and is specifically used for collections of enumerated types. The elements in EnumSet must come from the same enumeration class, which uses bit vectors to achieve efficient storage and operations.

Both classes are efficient implementations of enumeration type data.

Code example:

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

EnumMap<Day, String> activities = new EnumMap<>(Day.class);
activities.put(Day.MONDAY, "Working");
activities.put(Day.FRIDAY, "Partying");

EnumSet<Day> weekend = EnumSet.of(Day.SATURDAY, Day.SUNDAY);

49. What is IdentityHashMap?

Answer:
IdentityHashMap is a class in the java.util package that implements the Map interface. Unlike ordinary HashMap, it uses the referenced identity (memory address) instead of equals Method to determine key equality. This means that two keys are considered equal only if they refer to the same object.

IdentityHashMap is useful when you need to compare object references accurately, it does not consider the contents of the object, only the memory address of the object.

Code example:

IdentityHashMap<String, Integer> identityMap = new IdentityHashMap<>();
String key1 = new String("key");
String key2 = new String("key");
identityMap.put(key1, 1);

// key2不等于key1,所以不会被视为相等的键
identityMap.get(key2); // 输出 null

50. What is the Queue interface?

Answer:
The Queue interface is an interface in the java.util package and represents the queue data structure. Queues usually follow the "first-in-first-out" (FIFO, First-In-First-Out) principle, that is, the earliest element that enters the queue is removed first.

The Queue interface provides a series of methods for adding elements to the tail of the queue, removing elements from the head of the queue, and some methods for checking the status of the queue.

Commonly used Queue implementations include LinkedList, ArrayDeque and PriorityQueue.

51. What are the characteristics of the Map interface?

Answer:
The Map interface is an interface in the java.util package and is used to represent the mapping of key-value pairs. Map’s key features include:

  • Unique keys: Each key can only correspond to one value, and duplicate keys are not allowed.
  • Values ​​can be obtained by key: the corresponding value can be found by key.
  • Unordered: Maps generally do not guarantee a specific order of elements. Actual order may change over time.

Common implementations of the Map interface include HashMap, LinkedHashMap, TreeMap, etc.

52. What is NavigableMap interface?

Answer:
The NavigableMap interface is a sub-interface in the java.util package that extends the SortedMap interface. It provides a series of methods for navigation and search keys. The main features of NavigableMap include:

  • Methods are provided for searching for the smallest and largest keys.
  • Methods are provided for searching for a given key, or for keys greater or less than a given key.
  • Can get the previous and next key.

TreeMap is a common implementation of the NavigableMap interface.

53. What is EnumMap?

Answer:
EnumMap is a class in the java.util package that implements the Map interface and is specifically used when enumeration types are used as keys. EnumMap's keys must come from the same enum class, which makes it more efficient when having enum keys.

EnumMap uses arrays internally to represent

Mapping, therefore has higher access speed.

Code example:

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

EnumMap<Day, String> activities = new EnumMap<>(Day.class);
activities.put(Day.MONDAY, "Working");
activities.put(Day.FRIDAY, "Partying");

54. What is WeakHashMap?

Answer:
WeakHashMap is a class in the java.util package that implements the Map interface. It is a special Map in which the keys are "weak keys" Key). This means that if a key is no longer referenced by other parts, it will be collected by the garbage collector even if it still exists in the WeakHashMap.

WeakHashMap is often used to temporarily save a map of an object when there are no other strong references.

Code example:

WeakHashMap<Key, Value> weakHashMap = new WeakHashMap<>();
Key key = new Key();
Value value = new Value();
weakHashMap.put(key, value);

// 当key不再被强引用时,它会被垃圾回收,对应的映射也会被移除

55. What is PriorityQueue?

Answer:
PriorityQueue is a class in the java.util package that implements the Queue interface. It is a priority queue that arranges elements according to their priority. By default, PriorityQueue determines the priority of elements using their natural ordering or a provided comparator.

The implementation of PriorityQueue is based on the heap data structure, which ensures that the highest priority element in the queue is always at the head of the queue.

Code example:

PriorityQueue<Integer> priorityQueue = new PriorityQueue<>();
priorityQueue.add(5);
priorityQueue.add(3);
priorityQueue.add(7);

int highestPriority = priorityQueue.poll(); // 输出 3

56. What is Hashtable?

Answer:
Hashtable is an old class in the java.util package that implements the Map interface. It provides a way to store data using key-value pairs. Hashtable is functionally similar to HashMap, but it is thread-safe, that is, multiple threads can operate a Hashtable instance at the same time without causing concurrency problems.

However, since it is implemented based on synchronization methods, its performance is relatively poor in multi-threaded environments. After Java 5, it is more recommended to use ConcurrentHashMap to obtain better concurrency performance.

Code example:

Hashtable<String, Integer> hashtable = new Hashtable<>();
hashtable.put("one", 1);
hashtable.put("two", 2);

int value = hashtable.get("one");

57. What are WeakReference, SoftReference and PhantomReference?

Answer:
These are the reference types used for memory management in Java:

  • WeakReference (weak reference): A weak reference object will only be recycled when there is no strong reference pointing to it during garbage collection. Often used to implement caching to release some objects that are no longer needed when memory is low.
  • SoftReference: Soft reference objects may be recycled when memory is low, but only when memory is really tight. Used to build memory-sensitive caches.
  • PhantomReference (phantom reference): A phantom reference object may be garbage collected at any time. Virtual references are mainly used to track whether an object has been deleted from memory, but the object itself cannot be obtained through virtual references.

These reference types facilitate fine-grained memory management in specific scenarios.

58. What is the asList() method of Arrays class?

Answer:
The Arrays.asList() method is a static method in the java.util package, which can convert a passed set of elements into a fixed-size List. This List is a view and does not support adding or deleting elements, but you can use the set method to modify the value of the element.

Code example:

List<String> list = Arrays.asList("one", "two", "three");
list.set(0, "modified"); // 修改第一个元素为 "modified"

59. What is the unmodifiableXXX() method of Collections class?

Answer:
The Collections.unmodifiableXXX() method is used to create an unmodifiable collection, where XXX can be a List, Set or Map. These methods return an unmodifiable view, i.e. the original collection cannot be modified, but can be read.

Code example:

List<String> originalList = new ArrayList<>();
originalList.add("one");
originalList.add("two");

List<String> unmodifiableList = Collections.unmodifiableList(originalList);

// 尝试修改unmodifiableList会引发 UnsupportedOperationException

60. What is the singletonXXX() method of Collections class?

Answer:
The Collections.singletonXXX() method is used to create an unmodifiable collection containing only one element, where XXX can be a Set, List or Map. This kind of collection is more compact internally and is suitable for scenarios that only contain a single element.

Code example:

Set<String> singletonSet = Collections.singleton("Hello");
List<Integer> singletonList = Collections.singletonList(42);

61. What is the checkedXXX() method of Collections class?

Answer:
The Collections.checkedXXX() method is used to create a type-safe collection, where XXX can be a List, Set or Map. These methods help you ensure that the elements you add to the collection are of the correct type, thus avoiding type conversion errors at runtime.

Code example:

List<String> stringList = new ArrayList<>();
List checkedList = Collections.checkedList(stringList, String.class);

// 现在只能添加String类型的元素到checkedList

62. What is the sort() method of Arrays class?

Answer:
The Arrays.sort() method is a static method in the java.util package, used to sort array elements. It provides multiple overloaded methods that can be sorted according to different sorting rules. For basic type arrays, use Arrays.sort() to achieve fast sorting.

Code example:

int[] numbers = {5, 2, 8, 1};
Arrays.sort(numbers); // 对数组进行排序

63. What is the binarySearch() method of Arrays class?

Answer:
The Arrays.binarySearch() method is a static method in the java.util package and is used to perform binary search in a sorted array. If the array contains the target element, returns the index of the element; otherwise, returns a negative value indicating the position where the target element should be inserted.

Code example:

int[] numbers = {1, 2, 3, 5, 8};
int index = Arrays.binarySearch(numbers, 5); // 返回 3

64. What is the copyOf() method of Arrays class?

Answer:
The Arrays.copyOf() method is a static method in the java.util package, which is used to create a new array containing some or all elements of the specified array. The length of the new array can be longer or shorter than the original array.

Code example:

int[] original = {1, 2, 3, 4, 5};
int[] copy = Arrays.copyOf(original, 3); // 新数组为 {1, 2, 3}

65. What is the equals() method of Arrays class?

Answer:
The Arrays.equals() method is a static method in the java.util package, used to compare whether two arrays are equal. The elements in the array will be compared one by one. If the array lengths are equal and the elements at the corresponding positions are also equal, true will be returned, otherwise false will be returned.

Code example:

int[] array1 = {1, 2, 3};
int[] array2 = {1, 2, 3};

boolean areEqual = Arrays.equals(array1, array2); // 返回 true

66. What is hashCode() method of Arrays class?

Answer:
The Arrays.hashCode() method is a static method in the java.util package, used to calculate the hash code of an array. The hash code of an array is calculated based on the contents of the array. If two arrays have the same contents, their hash codes will be the same.

Code example:

int[] array = {1, 2, 3};
int hashCode = Arrays.hashCode(array); // 返回数组的哈希码

67. What is the toString() method of Arrays class?

Answer:
The Arrays.toString() method is a static method in the java.util package and is used to convert arrays into string representations. This method converts the elements into a string in array order, separated by commas, and placed within square brackets.

Code example:

int[] array = {1, 2, 3};
String arrayString = Arrays.toString(array); // 返回 "[1, 2, 3]"

68. What is the deepEquals() method of Arrays class?

Answer:
The Arrays.deepEquals() method is a static method in the java.util package, used to compare whether the contents of multi-dimensional arrays are equal. It recursively compares the elements of the array and returns true if the contents of the multidimensional array are exactly the same, otherwise it returns false.

Code example:

int[][] array1 = {
   
   {1, 2}, {3, 4}};
int[][] array2 = {
   
   {1, 2}, {3, 4}};

boolean areEqual = Arrays.deepEquals(array1, array2); // 返回 true

69. What is System.arraycopy() method?

Answer:
The System.arraycopy() method is a static method in Java, used to copy elements between arrays. It can copy part or all of the elements of an array to another array, and can place the copied elements starting at a specified position in the target array.

Code example:

int[] source = {1, 2, 3, 4, 5};
int[] target = new int[5];

System.arraycopy(source, 1, target, 2, 3); // 将 source[1] 到 source[3] 复制到 target[2] 到 target[4]

70. What is the fill() method of Arrays class?

Answer:
The Arrays.fill() method is a static method in the java.util package, which is used to fill specified values ​​into all elements of the array. This can be useful when initializing an array or clearing its contents.

Code example:

int[] array = new int[5];
Arrays.fill(array, 42); // 将数组的所有元素填充为 42

71. What is the stream() method of Arrays class?

Answer:
The Arrays.stream() method is a static method in the java.util package, which is used to convert an array into a stream object. By converting an array to a stream, you can take advantage of various stream operations to manipulate the elements in the array.

Code example:

int[] array = {1, 2, 3, 4, 5};
IntStream stream = Arrays.stream(array); // 将数组转换为 IntStream 流

72. What is the parallelSort() method of Arrays class?

Answer:
The Arrays.parallelSort() method is a static method in the java.util package, which is used to sort array elements in parallel. Compared with the ordinary Arrays.sort() method, the parallelSort() method performs sorting operations in parallel on multiple threads, thereby speeding up sorting.

Code example:

int[] array = {5, 2, 8, 1, 3};
Arrays.parallelSort(array); // 并行排序数组

73. What is the mismatch() method of Arrays class?

Answer:
The Arrays.mismatch() method is a static method in the java.util package, used to find the index of the first mismatched element in two arrays. If the arrays are exactly equal, -1 is returned.

Code example:

int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {1, 2, 3, 6, 7};

int mismatchIndex = Arrays.mismatch(array1, array2); // 返回 3

74. What is the frequency() method of Collections class?

Answer:
The Collections.frequency() method is a static method in the java.util package, used to count the number of occurrences of a specified element in a collection.

Code example:

List<String> list = Arrays.asList("apple", "banana", "apple", "orange");
int frequency = Collections.frequency(list, "apple"); // 返回 2

75. What is the disjoint() method of Collections class?

Answer:
The Collections.disjoint() method is a static method in the java.util package, which is used to determine whether two collections have no common elements. Returns true if the two collections have no elements in common, false otherwise.

Code example:

List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);

boolean areDisjoint = Collections.disjoint(list1, list2); // 返回 true

76. What is the reverse() method of Collections class?

Answer:
The Collections.reverse() method is a static method in the java.util package, used to reverse the order of elements in a collection.

Code example:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.reverse(list); // 将集合元素的顺序反转

77. What is the shuffle() method of Collections class?

Answer:
The Collections.shuffle() method is a static method in the java.util package, which is used to randomly shuffle the order of elements in the collection.

Code example:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.shuffle(list); // 随机打乱集合元素的顺序

78. What are the min() and max() methods of Collections class?

Answer:
The Collections.min() and Collections.max() methods are two static methods in the java.util package, used to find the minimum and maximum elements in the collection .

Code example:

List<Integer> list = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6);
int minValue = Collections.min(list); // 返回 1
int maxValue = Collections.max(list); // 返回 9

79. What is the addAll() method of Collections class?

Answer:
The Collections.addAll() method is a static method in the java.util package, used to add a set of elements to a collection. This method accepts a target collection and a set of elements as parameters and adds these elements to the target collection.

Code example:

List<String> list = new ArrayList<>();
Collections.addAll(list, "apple", "banana", "orange");

80. What is the synchronizedXXX() method of Collections class?

Answer:
The Collections.synchronizedXXX() method is a series of static methods in the java.util package, used to create thread-safe collections, where XXX can be List, Set or Map. These methods return a wrapped collection that is safe to use in a multi-threaded environment.

Code example:

List<String> list = new ArrayList<>();
List<String> synchronizedList = Collections.synchronizedList(list);

// synchronizedList 可以在多线程环境下安全操作

81. What is the spliterator() method of Arrays class?

Answer:
The Arrays.spliterator() method is a static method in the java.util package, used to create a split iterator (Spliterator) of an array. Split iterators can divide the elements of an array into multiple parts for parallel processing.

Code example:

int[] array = {1, 2, 3, 4, 5};
Spliterator.OfInt spliterator = Arrays.spliterator(array);

// 使用 spliterator 进行并行处理

82. What is the newSetFromMap() method of Collections class?

Answer:
The Collections.newSetFromMap() method is a static method in the java.util package, used to create a Set instance from an existing Map instance. The elements of this Set instance will be associated with the Map's key and therefore can only contain unique elements.

Code example:

Map<String, Boolean> map = new HashMap<>();
Set<String> set = Collections.newSetFromMap(map);

// set 中的元素将与 map 的键关联

83. What is the checkedMap() method of Collections class?

Answer:
The Collections.checkedMap() method is a static method in the java.util package. It is used to create a type-safe Map, in which the keys and values ​​need to comply with specific type. This helps you catch type errors at compile time.

Code example:

Map<String, Integer> map = new HashMap<>();
Map checkedMap = Collections.checkedMap(map, String.class, Integer.class);

// 只能将符合类型的键值对添加到 checkedMap

84. What is the emptyXXX() method of Collections class?

Answer:
The Collections.emptyXXX() method is a series of static methods in the java.util package, used to create empty collections, where XXX can be List, Set or Map .

Code example:

List<String> emptyList = Collections.emptyList();
Set<Integer> emptySet = Collections.emptySet();
Map<String, Integer> emptyMap = Collections.emptyMap();

85. What is the singletonMap() method of Collections class?

Answer:
The Collections.singletonMap() method is a static method in the java.util package, which is used to create an unmodifiable Map instance that contains only one key-value pair.

Code example:

Map<String, Integer> singletonMap = Collections.singletonMap("key", 42);

86. What is the nCopies() method of Collections class?

Answer:
The Collections.nCopies() method is a static method in the java.util package, which is used to create an unmodifiable List instance that contains the specified element repeated multiple times.

Code example:

List<String> copies = Collections.nCopies(3, "Hello");
// 创建一个包含 3 个 "Hello" 的 List

87. What is the reverseOrder() method of Collections class?

Answer:
The Collections.reverseOrder() method is a static method in the java.util package, which is used to obtain a comparator that performs the reverse order of elements. Compare.

Code example:

List<Integer> list = Arrays.asList(5, 2, 8, 1, 3);
Collections.sort(list, Collections.reverseOrder()); // 按逆序排序

88. What is the rotate() method of Collections class?

Answer:
The Collections.rotate() method is a static method in the java.util package, which is used to move elements in the collection cyclically. This method accepts a collection and a distance parameter, and circularly moves the elements in the collection the specified distance.

Code example:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.rotate(list, 2); // 循环移动 2 个位置

89. What is the replaceAll() method of Collections class?

Answer:
The Collections.replaceAll() method is a static method in the java.util package, which is used to replace all old values ​​​​in the collection with new values.

Code example:

List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "apple", "orange"));
Collections.replaceAll(list, "apple", "fruit");

// 将所有 "apple" 替换为 "fruit"

90. What is the singleton() method of Collections class?

Answer:
The Collections.singleton() method is a static method in the java.util package, used to create an unmodifiable Set instance containing only one element.

Code example:

Set<String> singletonSet = Collections.singleton("Hello");

91. What is the enumeration() method of Collections class?

Answer:
The Collections.enumeration() method is a static method in the java.util package, used to convert the specified collection into an enumeration (Enumeration) object. Enums are an old way of iterating, often used in legacy code.

Code example:

List<String> list = Arrays.asList("apple", "banana", "orange");
Enumeration<String> enumeration = Collections.enumeration(list);

92. What are the indexOfSubList() and lastIndexOfSubList() methods of Collections class?

Answer:
The Collections.indexOfSubList() and Collections.lastIndexOfSubList() methods are two static methods in the java.util package, used to find one collection in another collection The first and last index of the sublist.

Code example:

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 2, 3);
List<Integer> sublist = Arrays.asList(2, 3);

int firstIndex = Collections.indexOfSubList(list, sublist); // 返回 1
int lastIndex = Collections.lastIndexOfSubList(list, sublist); // 返回 5

93. What is the newXXX() method of Collections class?

Answer:
The Collections.newXXX() method is a series of static methods in the java.util package, used to create a modifiable empty collection, where XXX can be List or Set Or Map.

Code example:

List<String> newList = Collections.newLinkedList();
Set<Integer> newSet = Collections.newSetFromMap(new HashMap<>());
Map<String, Integer> newMap = Collections.newHashMap();

94. What is the checkedSortedMap() method of Collections class?

Answer:
The Collections.checkedSortedMap() method is a static method in the java.util package, used to create a type-safe ordered Map in which the keys and values ​​are Need to conform to a specific type. This helps you catch type errors at compile time.

Code example:

SortedMap<String, Integer> sortedMap = new TreeMap<>();
SortedMap checkedSortedMap = Collections.checkedSortedMap(sortedMap, String.class, Integer.class);

// 只能将符合类型的键值对添加到 checkedSortedMap

95. What are emptyIterator() and emptyListIterator() methods of Collections class?

Answer:
The Collections.emptyIterator() and Collections.emptyListIterator() methods are two static methods in the java.util package, used to create empty iterators (Iterator) and an empty ListIterator instance.

Code example:

Iterator<String> emptyIterator = Collections.emptyIterator();
ListIterator<Integer> emptyListIterator = Collections.emptyListIterator();

96. What is the fill() method of Collections class?

Answer:
The Collections.fill() method is a static method in the java.util package, which is used to fill all elements in the list with specified values.

Code example:

List<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
Collections.fill(list, 0); // 将列表的所有元素填充为 0

97. What is the unmodifiableCollection() method of Collections class?

Answer:
The Collections.unmodifiableCollection() method is a static method in the java.util package, which is used to create an unmodifiable collection view in which the elements are the same as the original collection. However, addition, deletion or modification operations cannot be performed.

Code example:

List<String> list = new ArrayList<>(Arrays.asList("apple", "banana", "orange"));
Collection<String> unmodifiableCollection = Collections.unmodifiableCollection(list);

// 尝试修改 unmodifiableCollection 会引发 UnsupportedOperationException

98. What is the disjoint() method of Collections class?

Answer:
The Collections.disjoint() method is a static method in the java.util package, which is used to determine whether two collections have no common elements. Returns true if the two collections have no elements in common, false otherwise.

Code example:

List<Integer> list1 = Arrays.asList(1, 2, 3);
List<Integer> list2 = Arrays.asList(4, 5, 6);

boolean areDisjoint = Collections.disjoint(list1, list2); // 返回 true

99. What is the singleton() method of Collections class?

Answer:
The Collections.singleton() method is a static method in the java.util package, used to create an unmodifiable Set instance containing only one element.

Code example:

Set<String> singletonSet = Collections.singleton("Hello");

100. What is the synchronizedCollection() method of Collections class?

Answer:
The Collections.synchronizedCollection() method is a static method in the java.util package, used to create a thread-safe collection whose elements are the same as the original collection. But it can be safely operated in a multi-threaded environment.

Code example:

List<String> list = new ArrayList<>();
Collection<String> synchronizedCollection = Collections.synchronizedCollection(list);

// synchronizedCollection 可以在多线程环境下安全操作

Guess you like

Origin blog.csdn.net/superfjj/article/details/132823343