A hashset is like a book, in which the keys are the summary and the values are the chapters.
In other words... When you insert an element into a hashset, a hash object. Hence you have a structure that stores information in pairs. Each pair has on one side the hash of the object and on the other side a pro object reference.
It turns out that hashes are usually well... random strings. For example, assuming the hash algorithm is the MD5:
- the hash of the string
foo
is acbd18db4cc2f85cedef654fccc4a4d8
;
- Already the hash of
bar
is 37b51d194a7513e45b56f6524f2d51f2
;
- And of
baz
is 73feffa4b7f6bb68e44cf984c85f6e88
.
If you were to sort the hashes alphabetically or hexadecimally, you would have to reindexe the set to each added element. This would slow the insertions, and one of the goals of the hashset is to be fast.
To complicate, it is possible to have hash collision. This occurs when two objects have the same hash. In this case, it is common for a hashset to add a little salt (this is a technical term!) to one of the objects and generate a new different hash for it. So the mess in the indexes gets even bigger.
You may want to use a chained hash map. This structure ensures the insertion order and there is a class in Java for this: http://docs.oracle.com/javase/7/docs/api/java/util/LinkedHashMap.html
Hashsets are not ordered (but it’s important to ask this and have an answer, so here’s a +1).
– Oralista de Sistemas
@Renan posted a code on my question..
– Pedro Rangel
@Pedrorangel Yes, your code is right. I think (it’s been a while since I’ve touched Java, I don’t really remember) that you can simplify it using
for ( Contato contato : contatos ) { ... }
(foreach). Remembering whenever the position returned may change in the course of the program, of course.– mgibsonbr
@mgibsonbr blz then^^
– Pedro Rangel