Alexey
Alexey

Reputation: 37

Does Set Of Sets on contain method checks the order?

My concern is if the Set of Sets (HashSet s) checks the order of items as well. I wrote the app that checks if the given Set of Integers exists in the Set of Sets of Integers

Somehow on one computer yesterday I noticed what Set of Integers is unordered (what is OK about HashSets) but I worried and wrote some simple main for check it :

public static void main(String[] args) {

    Set<Set<Integer>> set1 = new HashSet<Set<Integer>>();
    Set<Integer> set2 = new HashSet<Integer>();
    Set<Integer> set3 = new HashSet<Integer>();

    set3.add(14); set3.add(2); set3.add(9); set3.add(3); set3.add(5);

    set1.add(set3);

    set3 = new HashSet<Integer>();
    set3.add(6); set3.add(7); set3.add(8); set3.add(9); set3.add(10);   
    set1.add(set3);

    set2.add(9); set2.add(14); set2.add(5); set2.add(2); set2.add(3);

    System.out.println(set1);
    System.out.println(set2);
    if(set1.contains(set2)){
        System.out.println(":)");
    }else 
        System.out.println(":(");
}

The thing is I see what on this machine HashSet is ordered. Output is:

[[2, 3, 5, 9, 14], [6, 7, 8, 9, 10]]
[2, 3, 5, 9, 14]
:)

So my question is how Sets Compared? Bu values only? (sorry if the question sounds stupid.)

Upvotes: 3

Views: 79

Answers (2)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41210

HashSet does not guarantee that the order will remain constant over time. It is actually backed by a hash table. Which internally maintain bucket to store data, and it generate hash index of bucket by using hashing algorithm. Once you insert large number of data set you could see order may not be same. And It call equals method to check equality between two Object.

Upvotes: 0

Keppil
Keppil

Reputation: 46219

So my question is how Sets Compared? Bu values only?

Yes, the order is ignored when comparing two Sets. This is stated in the JavaDoc for Set#equals():

Compares the specified object with this set for equality. Returns true if the specified object is also a set, the two sets have the same size, and every member of the specified set is contained in this set (or equivalently, every member of this set is contained in the specified set). This definition ensures that the equals method works properly across different implementations of the set interface.

Upvotes: 2

Related Questions