| Author |
Hashset Custom object collection to String array
|
manish ahuja
Ranch Hand
Joined: Oct 23, 2003
Posts: 312
|
|
Hi there,
I have a custom java object with the attribute - (String name) used in the equals/hashCode method for determining the uniqueness.
Accordingly I build a Hashset of unique objects of the Custom class.
This hashset is a collection of the unique custom objects. What I want to grab is String array of only the unique identifier (i.e. attribute name).
How can I go about getting the same in a more easier way. Currently what i do is create a String array of the size of the hashset and then get a iterator to the hashset , traverse the elements, cast each element object , get the attribute and then add it to String array
Thanks,
|
 |
Gavin Tranter
Ranch Hand
Joined: Jan 01, 2007
Posts: 333
|
|
Not 100% sure what you are trying to do, but have you thought about using generics, so that the HashSet can only hold objects of your class type?
I think I would take a look at the methods available on HashSet and the Collections class and see if there is way of extracting an ArrayList from the HAshSet.
Hope that helps
Gavin
|
 |
manish ahuja
Ranch Hand
Joined: Oct 23, 2003
Posts: 312
|
|
yes the Hashset is generics based. HashSet<CustomDto>.
CustomDto {
String name;
String address;
int amount;
// equals and hashcode method on attribute name
}
The hashset I have is populated with objects of class CustomDto. What I am trying as mentioned in the initial post is to get a String array out of this Hashset so I get only the collection of unique names w/out the additional attributes.
I was looking for an effecient approach to achieve the same rather than using string array/iterator/traverse element/string array add option
Thanks,
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24081
|
|
No, there's no way to do it. If you were using a map instead of a set, with the identifier as the key, you could say something like
ArrayList list = new ArrayList(theHashMap.keySet());
but of course, internally it's going to be doing pretty much the same thing you're doing now. HashSet has some toArray() methods, of course, but these will only return the elements atually in the set.
|
[Jess in Action][AskingGoodQuestions]
|
 |
Gavin Tranter
Ranch Hand
Joined: Jan 01, 2007
Posts: 333
|
|
|
I think what I was thinking was, that as you know the type of the object, you dont need need the String array, you just for each over the collections calling object.getName().
|
 |
 |
|
|
subject: Hashset Custom object collection to String array
|
|
|