Athread-safeclass 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, somethread-safecollection classes includeStack,Vector,Properties,Hashtable, etc.
TheStackclass in Java implements a stack data structure based on theLIFOprinciple. Therefore, theStackclass supports many operations, such aspush, pop, peek, search, empty, etc.
import java.util.*; public class StackTest { public static void main (String[] args) { Stackstack = new Stack (); stack.push(5); stack.push(7); stack.push(9); Integer num1 = (Integer)stack.pop(); System.out.println("The element popped is: " + num1); Integer num2 = (Integer)stack.peek(); System.out.println(" The element on stack top is: " + num2); } }
The element popped is: 9 The element on stack top is: 7
Vector ## in Java #Class implements anarray of objects that grows as needed. The Vector class can supportadd(), remove(), get(), elementAt(), size()and other methodsExample
import java.util.*; public class VectorTest { public static void main(String[] arg) { Vector vector = new Vector(); vector.add(9); vector.add(3); vector.add("ABC"); vector.add(1); vector.add("DEF"); System.out.println("The vector is: " + vector); vector.remove(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!