File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Don't insert duplicate values Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Don Watch "Don New topic

Don't insert duplicate values

Mala Sharma
Ranch Hand

Joined: Oct 29, 2004
Posts: 76
I'm reading from a text file that looks like this:
001ASD034 | B21D43 | 04/30/2005
001CAN061 | D32J45 | 09/03/2004
001CAN061| D32J45 | 09/03/2004

I need to read the words in the line seperated by | which i did by:

i only need to store the unique lines. So, in the above case, i would only store the first and second line and leave out the third because it's same as the second. This the step, i'm stuck on. I was thinking to store the each word in a line in a string array and add that to the HashSet. But this would not work, as A new object of array class is created with every line so they will all appear different to the Hashset. Could someone please suggest how to approach this part of the problem. I'll be really grateful.

Mala Sharma
Ranch Hand

Joined: Oct 29, 2004
Posts: 76
I think i know what to do. I'll try it tomorrow and ask for help if there's any problem. Thanks.

Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

Well, you could create the Array for a line, and add the entire Array as an Object to your HashSet.


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
I can think of two options:

1) Use an ArrayList instead of an array. ArrayList overloads the equals() and hashCode() methods so that it will behave as you expect with HashSet.
2) Create a custom class to store the data in each line and overload equals() and hashCode() yourself.

I don't know for sure which is better. It mostly depends on what you need to do with the data after you read it from the file.


Java API Documentation
The Java Tutorial
I agree. Here's the link:
subject: Don't insert duplicate values
It's not a secret anymore!