Home >Java >javaTutorial >In Java, which collection classes are thread-safe?
A thread-safe class means that when multiple threads call it at the same time, it ensures that the internal state of the class and the value returned by the method are correct. . In Java, some thread-safe collection classes include Stack, Vector, Properties, Hashtable, etc.
The Stack class in Java implements a stack data structure based on the LIFO principle. Therefore, the Stack class supports many operations, such as push, pop, peek, search, empty, etc.
import java.util.*; public class StackTest { public static void main (String[] args) { Stack<Integer> stack = new Stack<Integer>(); stack.<strong>push</strong>(5); stack.<strong>push</strong>(7); stack.<strong>push</strong>(9); Integer num1 = (Integer)stack.<strong>pop</strong>(); System.out.println("The element popped is: " + num1); Integer num2 = (Integer)stack.<strong>peek</strong>(); System.out.println(" The element on stack top is: " + num2); } }
The element popped is: 9 The element on stack top is: 7
##Vector
Vector ## in Java #Class implements an array of objects that grows as needed . The Vector class can support add(), remove(), get(), elementAt(), size() and other methodsExample
import java.util.*; public class VectorTest { public static void main(String[] arg) { Vector vector = new Vector(); vector.<strong>add</strong>(9); vector.add(3); vector.add("ABC"); vector.add(1); vector.add("DEF"); System.out.println("The vector is: " + vector); vector.<strong>remove</strong>(1); System.out.println("The vector after an element is removed is: " + vector); } }
The vector is: [9, 3, ABC, 1, DEF] The vector after an element is removed is: [9, ABC, 1, DEF]
The above is the detailed content of In Java, which collection classes are thread-safe?. For more information, please follow other related articles on the PHP Chinese website!