简体   繁体   中英

How does HashSet sort?

I am practicing for the programming exam I have in a few weeks. One of the smaller tasks is to ask for user input (links) and add it to a unique list (set).

This is the way I did it (and it works):

DefaulListModel m = new DefaulListModel();
JList aList = new JList(m);
ArrayList<String> lenker = new ArrayList<String>();
Set<String> unique;

(...)

String url = JOptionPane.showInputDialog(null, "Skriv inn URL");
lenker.add(url);
unique = new HashSet<String>(lenker);
this.oppdaterGUI(liste, unique);

(...)

public void oppdaterGUI(JList liste, Set<String> array){
    m.clear();
    for(Object s : array){
        m.addElement((String) s);
    aList.setModel(m)
}

Here is my question: When I test it I entered the numbers 1,2,3,4,5,1

Now I would assume the ArrayList contains the numbers [1,5,4,3,2,1] And I would assume that after adding it to the HashSet it should look like {5,4,3,2,1}

But, it looks like this: {3,2,1,5,4}

Why are my assumptions wrong?

Edit: To clarify. I know that HashSet isn't sorted (that is TreeSet) but when I add the numbers, they are already sorted, why do they come out unsorted? I've done this multiple times, and every time they come out unsorted and exactly they same way. Each time.

So why are my assumptions wrong? I am just curious. It might be because my code sucks, I don't know, that's why I am asking here.

Set is not a sorted data structure. Nothing more to it :)

There are, however, Set implementations that have sorting mechanism. For example, treeset .


To answer your edit:

They come out unsorted because internally HashSet uses HashMap, that distributes the entries in buckets via some hashing algorithm. Those buckets are there checked in some order that is not guaranteed to stay the same.

Your HashSet comes out in unsorted order because each entry is hashed to be placed in a bucket . For a SortedSet (which HashSet is not), you could use TreeSet .

HashSet Internally uses hash-map, and hash-map does not guarantee that the order will remain constant over time.

if you are curious about the internal working of any class in Java then find src zip file under jdk installation folder and look inside.

HashSet is probably just an array, and using the hashing function to dictate which bucket to insert the value into. It guarantees uniqueness, but doesn't guarantee any order.

If you need the set to have insertion order ( for iterates in the same order that the numbers were inserted), use a LinkedHashSet . TreeSet is overkill when you don't need to keep the set sorted as you insert more and more numbers into it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM