3 Replies - 1189 Views - Last Post: 28 December 2011 - 09:53 AM Rate Topic: -----

#1 manyquestions  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 5
  • Joined: 28-December 11

Another stumper: how to convert hash set to an arraylist

Posted 28 December 2011 - 09:49 AM

Hi everyone, again.

Kind of similar to the other question I had earlier but regarding different data types. I created a hash set originally because I discovered the uberly cool feature that prevents duplicates. All has been well so far using this new data type for me however I can't go about SHUFFLEing it because it's not an arraylist. I tried searching for "how to shuffle a hash set" but it looks like you simply can't. Not that it's not possible but people don't.

So if I have a String set named "set" (which I fully plan on renaming later to a better name :D), how do I convert it into a String array list?

Thank you for your help! Data types can be tricky in Java, much trickier than Perl where it just knows what to do with pretty much everything.

Is This A Good Question/Topic? 0
  • +

Replies To: Another stumper: how to convert hash set to an arraylist

#2 GregBrannon  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1980
  • View blog
  • Posts: 4,824
  • Joined: 10-September 10

Re: Another stumper: how to convert hash set to an arraylist

Posted 28 December 2011 - 09:52 AM

Do you Google?

There are others.
Was This Post Helpful? 0
  • +
  • -

#3 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 9036
  • View blog
  • Posts: 33,508
  • Joined: 27-December 08

Re: Another stumper: how to convert hash set to an arraylist

Posted 28 December 2011 - 09:52 AM

Most Java Collections have a constructor that accepts another Collection as a parameter. So:
ArrayList<String> list = new ArrayList<String>(mySet);
Collections.shuffle(list);



Keep in mind a Set isn't indexed. The hashing determines where the elements go for HashSets. This is why you cannot shuffle them.
Was This Post Helpful? 2
  • +
  • -

#4 SwiftStriker00  Icon User is offline

  • Microsoft Insider
  • member icon

Reputation: 429
  • View blog
  • Posts: 1,596
  • Joined: 25-December 08

Re: Another stumper: how to convert hash set to an arraylist

Posted 28 December 2011 - 09:53 AM

Just follow this sample code:

Set<String> set = new HashSet<String>();
set.add("Dream");
set.add("In");
set.add("Code");
ArrayList<String> arrList= new ArrayList<String>(hashset);


This post has been edited by SwiftStriker00: 28 December 2011 - 09:56 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1