Re: Searching easiest way to convert/copy a (Hash)Set<--->List
On Jan 12, 9:39 am, Eric Sosman <esos...@ieee-dot-org.invalid> wrote:
On 1/12/2011 9:34 AM, Eric Sosman wrote:
On 1/12/2011 9:19 AM, Gianni Galore wrote:
Assume I have two variables:
List mylist = new List();
This won't compile, but "we know what you meant."
Set myhashset = new HashSet();
Assume I got a filled List. How can I convert/copy most easily the
content into a HashSet resp. vice versa?
myhashset.addAll(mylist) seems easy enough.
Missed the "vice versa:" mylist.addAll(myhashset). Note tha=
t
the original List's order will not necessarily be preserved: If you
start with a List of (A,B,C), put those into a Set {A,B,C}, and
extract to a List again you might get (C,A,B). That's because a
Set has no notion of "order," just of "membership."
Also, if the original List is (A,B,C,A), the Set (and the fina=
l
List) will have only three elements.
There's a wonderful help called the API Javadocs:
<http://download.oracle.com/javase/6/docs/api/java/util/List.html>
the briefest perusal of which shows
<http://download.oracle.com/javase/6/docs/api/java/util/
List.html#addAll(java.util.Collection)>
<http://download.oracle.com/javase/6/docs/api/java/util/Set.html>
the briefest perusal of which shows
<http://download.oracle.com/javase/6/docs/api/java/util/
Set.html#addAll(java.util.Collection)>
(not surprising, given that the method is required by
<http://download.oracle.com/javase/6/docs/api/java/util/
Collection.html#addAll(java.util.Collection)>
)
There are also constructors in the implementing classes you might
like:
<http://download.oracle.com/javase/6/docs/api/java/util/
ArrayList.html#ArrayList(java.util.Collection)>
<http://download.oracle.com/javase/6/docs/api/java/util/
HashSet.html#HashSet(java.util.Collection)>
to name two.
It's REALLY a good idea to study the collections types, and REALLY
even a better one to be in the habit of reading the Javadocs. You
won't be a good Java programmer until you do.
(Also, please stop cross-posting your questions.)
--
Lew