Sunday, 6 March 2016

How to convert an Array to HashSet in Java - Example Tutorial

The array was there in Java before the Collection framework makes its entry in JDK 1.4, hence, you will find several legacy code, which accepts array than the Collection or Set. Due to this, we often need to convert an array to different types of collection e.g. List or Set. Earlier, I have told you the trick to convert an array to list and today I'll teach you how to convert an array to HashSet by using the same technique. The concept you need to know is that Collection provides a copy constructor i.e. you can pass a collection to create another collection. We'll leverage the same fact and to create an HashSet, we'll pass an ArrayList. Since you can use Arrays.asList() to convert an array to ArrayList, converting an array to HashSet is just two step job, first convert an array to a list and then convert a list to set.
Read more »

No comments:

Post a Comment