InterviewSolution
| 1. |
Which collection classes are thread-safe in Java |
|
Answer» The collection classes that are thread safe in Java are Stack, Vector, Properties, Hashtable ETC. Details about some of these collection classes are given as follows: Stack class in Java The Stack class in Java implements the stack data structure that is based on the principle of LIFO. So, the stack class can provide many operations such as push, pop, peek, search, empty etc. A program that demonstrates the Stack class is given as follows: import java.io.*; import java.util.*; public class Demo { public STATIC void main (String[] ARGS) { Stack<Integer> stack = new Stack<Integer>(); stack.push(4); stack.push(1); stack.push(9); Integer num1 = (Integer) stack.pop(); System.out.println("The element popped is: " + num1); Integer num2 = (Integer) stack.peek(); System.out.println("Element on stack TOP is: " + num2); } }The output of the above program is as follows: The element popped is: 9 Element on stack top is: 1Vector class in Java An array of OBJECTS that grows as required is implemented by the Vector class in Java. A program that demonstrates the Vector class is given as follows: import java.util.*; public class Demo { public static void main(String[] arg) { Vector vector = new Vector(); vector.add(9); vector.add(3); vector.add("Apple"); vector.add(1); vector.add("Mango"); System.out.println("The vector is: " + vector); vector.remove(1); System.out.println("The vector after element at index 1 is removed is: " + vector); } }The output of the above program is as follows: The vector is: [9, 3, Apple, 1, Mango] The vector after element at index 1 is removed is: [9, Apple, 1, Mango] |
|