Non-unique element in HashSet
Hello,
I have a problem with the class HashSet, I redefined the equals method for a class that I use, and yet if I insert two different objects with similar attributes, the second is not rejected is to say that the HashSet does not see it already contained. I have a question for you , are there non-unique elements in the Hashset. If this can be done in the HashSet, then please post back. Waiting for the reply. The HashSet is not based Does not the equals method of the object? If ever I tried with a TreeSet, and there is no problem. Any more help on this will be highly appreciated. Thanks in advance.
Re: Non-unique element in HashSet
Hello,
I an new to this concept in java, even I have tried some of the code for this. I have one code for you, I think you will be interested in this.
Code:
HashSet s = new HashSet();
VirtualFile f1 = new VirtualFile(C:\\text.txt ", false);
VirtualFile f2 = new VirtualFile(C:\\text.txt ", false);
System.out.System.out.println("f1 equals f2?" + F1.equals(f2));
HashSet.add(f1);
System.out.System.out.println("f2 in HashSet?" + HashSet.contains(f2));
Re: Non-unique element in HashSet
Hello,
For now, your prog say that the method is not in the HashSet (and that's what you want, right?). Well, it looks like you've forgotten your example to add in your HashSet, but if not, it works well as you wish, or so I have not understood your problem. I you need more help on this , or want to know the full list of methods and the classes available in java, then you can visit the sun's official site and there you can view all the methods and classes with the brief description.
Re: Non-unique element in HashSet
Hello,
Just check out the following part of code, I think this is what you are asking about.
Code:
Public boolean equals(Object ele) {
if (ele instanceof VirtualFile)
return ((VirtualFile) ele).getPath().equals(this.getPath());
else
return false;
}
The above method will return a String, and If I am correct this is what you want from your program.
Re: Non-unique element in HashSet
Hello,
It is true that I mixed up a bit. But I have not forgotten to include the method and the other one too, by the way they are the same (in terms of the equals method in all cases), In the above example also after F1 has been inserted the test is supposed referred also true for f2. I think this is the proper logic which I have to use in my code. Thanks for you help. If you have any more information on this then please let me know, I am interested.
Re: Non-unique element in HashSet
Hello,
The problem is that you have not overloaded the method hashCode () in your class VirtualFile which allows a quick comparison of indexing before the algo might go further and test the equals () that have successfully test indexing
Here's an example assuming that getPath () returns a String:
Code:
Public class VirFl {
Public int hashCode() {
return getPath().hashCode();
}
}
Hope this will help you.