How to use java.Set

前端 未结 4 1973
误落风尘
误落风尘 2020-12-08 16:33

I\'m trying to make it working for quite some time,but just can\'t seem to get it. I have object Tower built of Block\'s. I\'ve already made it working using arrays, but I w

4条回答
  •  一整个雨季
    2020-12-08 17:21

    The first thing you need to study is the java.util.Set API.

    Here's a small example of how to use its methods:

        Set numbers = new TreeSet();
    
        numbers.add(2);
        numbers.add(5);
    
        System.out.println(numbers); // "[2, 5]"
        System.out.println(numbers.contains(7)); // "false"
    
        System.out.println(numbers.add(5)); // "false"
        System.out.println(numbers.size()); // "2"
    
        int sum = 0;
        for (int n : numbers) {
            sum += n;
        }
        System.out.println("Sum = " + sum); // "Sum = 7"
    
        numbers.addAll(Arrays.asList(1,2,3,4,5));
        System.out.println(numbers); // "[1, 2, 3, 4, 5]"
    
        numbers.removeAll(Arrays.asList(4,5,6,7));
        System.out.println(numbers); // "[1, 2, 3]"
    
        numbers.retainAll(Arrays.asList(2,3,4,5));
        System.out.println(numbers); // "[2, 3]"
    

    Once you're familiar with the API, you can use it to contain more interesting objects. If you haven't familiarized yourself with the equals and hashCode contract, already, now is a good time to start.

    In a nutshell:

    • @Override both or none; never just one. (very important, because it must satisfied property: a.equals(b) == true --> a.hashCode() == b.hashCode()
      • Be careful with writing boolean equals(Thing other) instead; this is not a proper @Override.
    • For non-null references x, y, z, equals must be:
      • reflexive: x.equals(x).
      • symmetric: x.equals(y) if and only if y.equals(x)
      • transitive: if x.equals(y) && y.equals(z), then x.equals(z)
      • consistent: x.equals(y) must not change unless the objects have mutated
      • x.equals(null) == false
    • The general contract for hashCode is:
      • consistent: return the same number unless mutation happened
      • consistent with equals: if x.equals(y), then x.hashCode() == y.hashCode()
        • strictly speaking, object inequality does not require hash code inequality
        • but hash code inequality necessarily requires object inequality
    • What counts as mutation should be consistent between equals and hashCode.

    Next, you may want to impose an ordering of your objects. You can do this by making your type implements Comparable, or by providing a separate Comparator.

    Having either makes it easy to sort your objects (Arrays.sort, Collections.sort(List)). It also allows you to use SortedSet, such as TreeSet.


    Further readings on stackoverflow:

    • Overriding equals and hashCode in Java
    • When to use Comparable vs Comparator

提交回复
热议问题