Home > Java > javaTutorial > body text

In Java, which collection classes are thread-safe?

WBOY
Release: 2023-08-18 21:41:13
forward
1178 people have browsed it

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.

Stack

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.

Example

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);
   }
}
Copy after login

Output

The element popped is: 9
The element on stack top is: 7
Copy after login

##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);
   }
}
Copy after login

Output

The vector is: [9, 3, ABC, 1, DEF]
The vector after an element is removed is: [9, ABC, 1, DEF]
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template