Set interface and collection traversal

Keywords: Java

Set interface

Set set is another interface belonging to Collection. The objects in the set are not sorted in a specific way, but simply placed in the set, but the set set can not contain duplicate objects. Set collection consists of implementation classes of Set interface. The Set interface inherits the Collection interface and therefore contains all the methods of the Collection interface. HashSet and TreeSet are the main implementations of Set interface. The difference between them lies in:

  • The HashSet class implements the Set interface, which is supported by the hash table. It does not guarantee the iteration order of Sets, especially that it does not guarantee that the order will remain constant. This class allows null elements to be used

  • The TreeSet class implements not only the Set interface, but also the java.util.SortedSet interface (note that Collection is located in the java.lang.Object package). Therefore, the set set set implemented by the TreeSet class is sorted incrementally in natural order when traversing the set, or incrementally in accordance with the specified comparator, that is, the objects in the set set set set set implemented by the TreeSet class can be sorted by the comparator.

    Custom implementation HashSet:

import java.util.HashMap;

public class MyHashSet {
    /**
     * Customize your own HashSet
     * set The non-repeatability is the use of the non-repeatability of key objects in map!
     */
    HashMap<Object, Object> map;
    private static final Object PRESENT = new Object();

    public MyHashSet(){
        map = new HashMap<Object, Object>();
    }

    public int size(){
        return map.size();
    }

    public void add(Object o){
        map.put(o, PRESENT);   //The non-repeatability of set makes use of the non-repeatability of key objects in map.
    }

    public static void main(String[] args) {
        MyHashSet s = new MyHashSet();
        s.add("aaa");
        s.add(new String("aaa"));
        System.out.println(s.size());//1
    }
}

Iterator interface (traversing objects in a collection)

Iterator is a design pattern, it is an object, it can traverse and select objects in the sequence, and developers do not need to understand the underlying structure of the sequence. Iterators are often referred to as "lightweight" objects because of the low cost of creating them. The Iterator function in Java is relatively simple and can only move in one direction. All container classes that implement the Collection interface have an iterator method to return an object that implements the Iterator interface. It has only three ways:

  1. boolean hashNext(); //Determine whether an element has not been traversed
  2. Object next(); //Returns the element of the cursor's current position and moves the cursor to the next position
  3.  void remove(); //Delete the element to the left of the cursor, which can only be performed once after next.

An ordered Set like List may be traversed in other ways, but the Set set Set is disordered, so it must be traversed with the help of the Iterator interface.

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class Test06 {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add(13);
        list.add(22);
        list.add(33);

        //Traversing List s by Index
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }
        //Traversing List s through Iterators
        for(Iterator iter1 = list.iterator();iter1.hasNext();){
            String str = (String) iter1.next();
            System.out.println(str);
            iter1.remove();
        }

        Set set = new HashSet();
        set.add("1");
        set.add("2");
        set.add("3");
        Iterator it = set.iterator();
        while(it.hasNext()){
            System.out.println((String)it.next());
        }
        System.out.println("=====================");
        //Here's another use of iterators
//      for(set.iterator();it.hasNext();){
//          String str = (String)it.next();
//          System.out.println(str);
//      }
    }
}
//Source Code Analysis of Iterator
private class Itr implements Iterator<E> {
        int cursor = 0;

        int lastRet = -1;

        public boolean hasNext() {
            return cursor != size();
        }

        public E next() {
            try {
                int i = cursor;
                E next = get(i);
                lastRet = i;
                cursor = i + 1;
                return next;
            } catch (IndexOutOfBoundsException e) {
                checkForComodification();
                throw new NoSuchElementException();
            }
        }

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();
            try {
                AbstractList.this.remove(lastRet);
                if (lastRet < cursor)
                    cursor--;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException e) {
                throw new ConcurrentModificationException();
            }
        }

Posted by knucklehead on Sat, 25 May 2019 14:02:11 -0700