Home> Java> javaTutorial> body text

In Java, which collection classes are thread-safe?

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

In Java, which collection classes are thread-safe?

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.

Stack

TheStackclass in Java implements a stack data structure based on theLIFOprinciple. Therefore, theStackclass supports many operations, such aspush, pop, peek, search, empty, etc.

Example

import java.util.*; public class StackTest { public static void main (String[] args) { Stack stack = 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); } }
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 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); } }
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!