after that I would like to print this data and I'm trying with this code:
And of course it doesn0t work, I get something like:
How do I print my hashSet?
Thanks in advance!
To print the contents, you're going to have to render each individual item somehow. You might do this with another loop inside the first, or you could use java.util.Arrays.asList() to turn the String into a List<String>, which will, if printed, display the Strings in the array.
Originally posted by Rob Prime:
1) You are adding the exact same instance of the string array to the set. Because it is a set, there will always be only one element.
2) See Ernest's comment; this also solves issue 1.
3) You can use Arrays.toString(...) to nicely print an array.
Ok, I was in a hurry yesterday so I'll try to explain my problem again.
I'm trying to read some data from text files(no problems with this), specifically first name and last name. I want to put this data in a sort of collection that cannot contain duplicates, and that's why I chose hashSet. So if I come across a same first name and last name more than once I don't want it to be added in the collection. Afterwards I need to print this data.
Can you give me a simple solution to do this?
If you create a new String array in each loop, then wrap it in a list by calling Arrays.asList(), this should do what you need. The list returned by Arrays.asList() has an equals method that performs the following checks:
- return false if the object to compare with is not a list
- iterate through both lists and check if they have the same elements in the same order
Seeing as both will be the case this should work just fine.
Because you will add lists you won't need to do any fancy stuff to get a nice printed version; the list will print itself as [element0, element1].