Skip to main content

Posts

Showing posts with the label HashSet

Collection Interview Questions

Q1) What is difference between ArrayList and Vector? Ans: ) 1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe. 2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent. Q2) How can Arraylist be synchronized without using Vector? Ans) Arraylist can be synchronized using: Collection.synchronizedList(List list) Other collections can be synchronized: Collection.synchronizedMap(Map map) Collection.synchronizedCollection(Collection c)

How to Convert an ArrayList to a HashSet?

-- This code example shows how to convert ArrayList to HashSet: import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class ArrayListToHashSet { public static void main(String[] args) { List list = new ArrayList (); list.add(null); list.add("A"); list.add("B"); Set hashset = new HashSet (list); list = new ArrayList (hashset); System.out.println(list.toString()); } }

How to Convert a HashSet to an ArrayList?

-- This code example shows how to convert HashSet to ArrayList: import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; public class HashSetToArrayList { public static void main(String[] args) { Set hashset = new HashSet (); hashset.add("A"); hashset.add("B"); hashset.add("C"); List list = new ArrayList (hashset); System.out.println(list.toString()); } }