A Preliminary Study of Java Class Set

Posted by Foregone96 on Sat, 20 Jul 2019 14:52:17 +0200

Class Set

  • Class Set: The main function is the implementation of Java data structure (java.util)
  • Class sets are dynamic object arrays (linked lists are also dynamic arrays)

Collection interface*

  • Collection is the largest single-valued parent interface in the entire class set. That is, only one object can be saved to the collection at a time.
public interface Collection<E>
extends Iterable<E>
  • Common methods of operation defined in Collection

Common operating methods

  • Save data to a collection
public  boolean add(E e);
  • Adding a set
public boolean addAll(Collection<? extends E>c);
  • Clear set (root element null)
public void clear();
  • Determine whether there is a specified content
public boolean contains(Object o);
  • Judging whether it is an empty set
public boolean isEmpty();
  • delete object
public boolean remove(Object o);
  • Get the number of elements
public int size();
  • Save the collection as an array of objects
public Object [] toArray();
  • Instantiate the Iterator interface
public Iterator<E> iterator();

contains() and remove() must rely on equals() support;

List subinterface

  • List sub-interface is the most commonly used sub-interface in Collection interface.
  • List extends the Collection interface.

Common Operations

  • Get the contents of the index number
public E get(int index);
  • Modify the contents of the index
public E set(int index , E element);
  • Instantiating objects for the LisIterator interface
public ListIterator<E> listIterator();

List belongs to the interface, if you want to use the interface to operate, you must have subclasses; you can use ArrayList subclasses to implement (and Vector subclasses)

ArrayList subclass

    public static void main(String [] args) throws IOException {
        List<String> all = new ArrayList<String>();
        System.out.println("size:" + all.size() + "Null:" + all.isEmpty());
        all.add("Hello");
        all.add("Hello");
        all.add("World");
        System.out.println("size:" + all.size() + "Null:" + all.isEmpty());
        // Collection interface defines size() method to get collection length
        // List subinterface adds get() method to retrieve all data
        for (int x = 0 ; x < all.size() ; x++) {
            String str = all.get(x);
            System.out.println(str);
        }
    }
}

By analyzing the use of the ArrayList() subclass, the data stored in the List collection is stored in the order of preservation, and repetitive data is allowed; the List subinterface has get() method, which can obtain the content of the specified sequence in the collection.

  • Instance for Collection Interface
public class TestDemo {
    public static void main(String [] args) throws IOException {
        Collection<String> all = new ArrayList<String>();
        System.out.println("size:" + all.size() + "Null:" + all.isEmpty());
        all.add("Hello");
        all.add("Hello");
        all.add("World");
        System.out.println("size:" + all.size() + "Null:" + all.isEmpty());
        Object[] obj = all.toArray();//Change to an object array to read data
        for (int x = 0 ; x < obj.length ; x ++) {
            System.out.println(obj[x].toString());
        }
        /*for (int x = 0 ; x < all.size() ; x++) {
            String str = all.get(x);// Because there is no get() method in the Collection class, it cannot be used
            System.out.println(str);
        }*/
    }
}
  • List saves objects
class Book {
    private String title ; 
    private double price ;
    public Book(String title , double price) {
        this.price = price;
        this.title = title;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true ; 
        }
        if (obj == null) {
            return false;
        }
        if(!(obj instanceof Book)) {
            return false ; 
        }
        Book book = (Book) obj;
        if (this.title.equals(book.title) && this.price == book.price){
            return true;
        }
        return false;
    }
    @Override
    public String toString() {
        return this.title + "\t" + this.price + "\n";
    }
}

public class TestDemo {
    public static void main(String [] args) {
        List<Book> all = new ArrayList<Book>();
        all.add(new Book("Java",11.1));
        all.add(new Book("python",22.2));
        all.add(new Book("C/C++",33.3));
        all.add(new Book("PHP",44.4));
        // Remember: remote and contains methods need to override equls() classes in classes
        all.remove(new Book("PHP",44.4));
        System.out.println(all);
    }
}

Vector subclass (old)

  • Difference:

    The Vector subclass is thread-safe by synchronization, while the ArrayList subclass is asynchronous by non-thread-safe mechanism. ArrayList supports Iterator, ListIterator, foreach output, and Vector also supports Enumeration.

Summary:

  • The order of data preservation in List is the order of data addition.
  • Allowing duplicate elements to be stored in a List collection
  • List subinterface extends get(), set() methods over Collection
  • Lists are mostly manipulated using ArrayList subclasses

Set subinterface

The Set sub-interface simply inherits the Collection interface, and does not follow the List interface to expand the functionality of the original interface.

  • Common subclasses: HashSet, TreeSet

  • Observe the HashSet subclass:

public class TestDemo {
    public static void main(String [] args) {
        Set<String> all = new HashSet<String>();
        all.add("Hello");
        all.add("Hello");//Do not save duplicate data
        all.add("World");
        all.add("HUAWEI");
        System.out.println(all + ">>>" + all.size());
    }
}

Through observation, it is found that there are no duplicate data elements (the characteristics of Set sub-interface) in Set set, that is, the features of HashSet sub-class belong to disordered arrangement.

  • Observe the TreeSet subclass:
public class TestDemo {
    public static void main(String [] args) {
        Set<String> all = new TreeSet<String>();
        all.add("Hello");
        all.add("Hello");//Do not save duplicate data
        all.add("World");
        all.add("Array");
        System.out.println(all + ">>>" + all.size());
    }
}

It is concluded that there is no duplicate data in the TreeSet subclass and the stored content is automatically ascending by default.

Data Sorting Problem

class Book implements Comparable<Book>{
    private String title ; 
    private double price ; 
    public Book(String title , double price) {
        this.title = title;
        this.price = price;
    }
    @Override
    public String toString() {
        return this.title + "\t" + this.price;
    }
    /*
     * Sets are essentially dynamic object arrays, while dynamic object arrays are sorted using comparators
     * So we use comparable comparator
     * 
     * Because there are duplicate elements, compareTo will be considered the same object, (the characteristics of the Set sub-interface)
     * So the repeated interpretation of set sub-interface depends on Comparable.
     * For this reason, we can use String's compareTo method to compare with the same object.
     */
    @Override
    public int compareTo(Book o) {
        if (this.price > o.price) {
            return 1;   
        } else if(this.price < o.price) {
            return -1;
        } else {
            // We call compareTo method of String class to compare
            return this.title.compareTo(o.title);
        }
    }
}

public class TestDemo {
    public static void main(String [] args) {
        Set<Book> all = new TreeSet<Book>();
        all.add(new Book("Java",11.1));
        all.add(new Book("Java",11.1));     //Complete repetition of information
        all.add(new Book("php",11.1));      //Partial duplication of information
        all.add(new Book("Python",33.3));   //Information is completely non-repetitive
        System.out.println(all);
    }
}

Through observation, it is found that the Comparable interface supports the judgment of repetitive data of TreeSet class and does not support the interpretation of repetitive data of HashSet class.

Repetitive Element Problem

Through the above code, we find that Comparable interface (comparator) is only responsible for the judgment of repetitive elements of TreeSet subclass; (relying on comparTo() method, if the same data is found, the same object element is judged, then return 0;)

If you want to judge the duplication of data elements, you can only rely on the method in Object:

  • Getting Hash Code
public int hashCode();
  • Object comparison
public boolean equals(Object obj);

Code:

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        long temp;
        temp = Double.doubleToLongBits(price);
        result = prime * result + (int) (temp ^ (temp >>> 32));
        result = prime * result + ((title == null) ? 0 : title.hashCode());
        return result;
    }


    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Book other = (Book) obj;
        if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
            return false;
        if (title == null) {
            if (other.title != null)
                return false;
        } else if (!title.equals(other.title))
            return false;
        return true;
    }
  • Summary:

    In order to determine whether the elements are duplicated or not, the hashCode() and equals() in Object method are used.

Summary:

  • Set subinterface is not recommended in development, and HashSet class is also recommended if used.
  • Comparable comparator is widely used in Java theory

Set Output

Collection, List and Set are three interfaces. List interface is the most conducive to output operation (ArrayList subclass). Therefore, the output of this set is:

Iterator*: Iterative output

public interface Iterator<E> {
    public boolean hasNext();
    public E next<E>();
} 

Iterator is an interface. If you want to instantiate an interface, you need to rely on the Collection interface iterator() method.

public Iterator<E> iterator();// java.util.Collection
public class TestDemo {
    public static void main(String [] args) {
        Set<String> all = new HashSet<String>();//Set subinterface
        all.add("Mirror");
        all.add("wangyuyang");
        all.add("wangyuyang");
        Iterator<String> iter = all.iterator();// Instance interface
        while (iter.hasNext()) { //Judge whether it is empty
            String str = iter.next();// Getting element data
            System.out.println(str);
        }
    }
}

Set features automatically do not retain duplicate data and do not output in an orderly manner

public class TestDemo {
    public static void main(String [] args) {
        List<String> all = new ArrayList<String>();//List subinterface
        all.add("Mirror");
        all.add("wangyuyang");
        all.add("wangyuyang");
        Iterator<String> iter = all.iterator();// Instance interface
        while (iter.hasNext()) { //Judge whether it is empty
            String str = iter.next();// Getting element data
            System.out.println(str);
        }
    }
}

Display all added elements and add sequential output as it is

  • The output problem of sets:

    When you encounter the output problem of a set, you can use the Iterator interface directly for output.

ListIterator: Two-way iteration

  • Iterator itself only has "forward-backward" output, while the ListLterator sub-interface supports bidirectional iteration.

  • Determine whether there is a previous element: (reverse)

public boolean hasPreviout();
  • Get the previous element: (reverse)
public E previous();
  • List method of instance ListIterator interface:
public ListIterator<E> listIterator();
public class TestDemo {
    public static void main(String [] args) {
        List<String> all = new ArrayList<String>();//Set subinterface
        all.add("A");
        all.add("B");
        all.add("C");
        System.out.println("Forward Iterative Output");
        ListIterator<String> iter = all.listIterator();
        while (iter.hasNext()) { //Judge whether it is empty
            String str = iter.next();// Getting element data
            System.out.println(str);
        }
        System.out.println("***********");
        System.out.println("Reverse Iterative Output");
        while(iter.hasPrevious()) {
            System.out.println(iter.previous());
        }
    }
}

The above example realizes the function of bidirectional iteration; uses hasNet() method to judge whether it is empty, next() method to output element content, and realizes forward iteration output; and uses hasPrevious() and revious () method in ListIterator interface to realize reverse iteration output.

  • Be careful:

If we use ListIterator interface to achieve reverse iteration output, we need to first carry out forward iteration output; that is to say, we must achieve forward iteration output before realizing reverse iteration output.

Enumeration: Enumeration output

The output interface published by both the Enumeration and Vector classes; the collection defined by the early Vector classes requires Enumeration to output.

  • Interface definition
public interface Enumberation<E>{
    public boolean hasMoreElements(); //Determine if there is the next element
    public E nextElement(); // Get the current element content
}
  • Instantiating Enumeration Interface Objects can only rely on Vector subclasses
public Enumeration<E> elements() // Get the Enumeration interface object
public class TestDemo {
    public static void main(String [] args) {
        Vector<String> all = new Vector<String>();//Set subinterface
        all.add("A");
        all.add("B");
        all.add("C");
        Enumeration<String> enu = all.elements();
        while(enu.hasMoreElements()) {
            System.out.println(new String(enu.nextElement()));
        }
    }
}

foreach output

public class TestDemo {
    public static void main(String [] args) {
        List<String> all = new ArrayList<String>();//Set subinterface
        all.add("A");
        all.add("B");
        all.add("C");
        for (String str : all) {
            System.out.println(str);
        }
    }
}

Map interface

Collection stores an object each time, and the Map interface is mainly responsible for a pair of objects.

Main operating methods

  • Save data to a collection
public V put(K key , V value);
  • Find Value according to Key
public V get(Object key);
  • Combining Map s into Set Sets
public Set<Map Entry<K,V>> entrySet();
  • Remove all Key values
public Set<K> keySet();
  • Common subclasses:
    • HashMap
    • Hashtable

Observation of HashMap

public class TestDemo {
    public static void main(String [] args) {
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("one", 1);
        map.put("Bitch", 2);
        map.put("three", 3);
        map.put("three", 33);
        System.out.println(map);
    }
}

Through code analysis, it can be found that the output implemented by HashMap is out of order; duplicate keys found will be overwritten, and the value of the new content key will override the original value.

  • Application of get method
public class TestDemo {
    public static void main(String [] args) {
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("one", 1);
        map.put("Bitch", 2);
        map.put(null, 3);
        System.out.println(map.get("one")); //Return 1
        System.out.println(map.get("Lu"));//key does not exist to return null
        System.out.println(map.get(null));// Return 3
    }
}

Through the code observation of HashMap and get() method, it is found that the main purpose of Map is to find the information of data, and the main purpose of Collection is to achieve the output of information data.

  • Get all key values:
public class TestDemo {
    public static void main(String [] args) {
        Map<String,Integer> map = new HashMap<String,Integer>();
        map.put("one", 1);
        map.put("Bitch", 2);
        map.put("three", 3);
        Set<String> set = map.keySet();// Get key
        Iterator<String> iter = set.iterator();
        while(iter.hasNext()) {
            System.out.println(iter.next());//Output all key s
        }
    }
}

Observation of Hashtable

public class TestDemo {
    public static void main(String [] args) {
        Map<String,Integer> map = new Hashtable<String, Integer>();
        map.put("one", 1);
        map.put("Bitch", 2);
        map.put("three", 3);
        System.out.println(map);
    }
}

The difference between Hashtable and HashMap subclasses is compared by setting key or value as Null values: Hashtable subclasses do not allow null values, while HashMap allows null values in Key or Value. *

Iterator Output Problems (Focus)

  • When it comes to the output of a set, it is necessary to use Iterator for output; however, the method of returning Iterator interface object is not defined in Map interface, so using Iterator output for Map data needs to convert the Map set to Set set.

  • In the Collection interface, Iterator gets a complete Collection object; Map is different, but when Map.put() stores a pair of data in the collection, it automatically encapsulates it as a Map.Entry interface object.

public static interface Map.Entry<K,V>;//(Equivalent to an external interface)
  • Map.Entry Interface Operating Method
    • getkey(): Gets the Key value
    • getValue(): Gets the Value value

Save in Map is actually an object wrapped by the Map.Entry interface, which wraps data elements with Key and Value values.

  • As mentioned above, if Iterator takes out the output data, it is an object (in the Collection interface, it is essentially the object of Collection), while in the Map interface, it takes out a Map.Entry interface object, and then gets Key and Value.
  • In Map, a method of converting a Map set to a Set is defined.
public Set<Map.Entry<K,V>> entrySet();
  • When you convert to a Set collection, you can call the Iterator output.

  • Using the Map interface EntrySet() method to change the Map combination into Set set --> iterator() method in Set combination is used to output Set --> Each set element extracted is Map.Entrty interface object, which is used to extract Key and Value.

Using Iterator to Implement Map Interface Output*

public class TestDemo {
    public static void main(String [] args) {
        Map<String,Integer> map = new Hashtable<String, Integer>();
        map.put("one", 1);
        map.put("Bitch", 2);
        map.put("three", 3);
        // Turn Map Collection into Set Combination
        Set<Map.Entry<String, Integer>> set = map.entrySet();
        // Instantiating Set Collections into iterator Interface Objects
        Iterator<Map.Entry<String, Integer>> iter = set.iterator();
        while(iter.hasNext()) {
            // Because the iter content holds the object of the Map.Entry interface, the Key and Value are removed using the Map.Entry object.
            Map.Entry<String, Integer> men = iter.next();
            System.out.println(men.getKey() + "==" + men.getValue());
        }
    }
}

Key in Map Collection

The type of Key can be customized using the Map collection; then this customized type must override hashCode() and equals() methods in the Object class, because only these two methods can determine whether the elements are duplicated. [The first key type is String, try not to use custom object types to define key; because hashCode() and equals() are defaulted in String classes]

class Book{
    private String title ; 
    public Book(String title) {
        this.title = title;
    }
    @Override
    public String toString() {
        return this.title;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((title == null) ? 0 : title.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Book other = (Book) obj;
        if (title == null) {
            if (other.title != null)
                return false;
        } else if (!title.equals(other.title))
            return false;
        return true;
    }
    
}

public class TestDemo {
    public static void main(String [] args) {
        Map<Book,String> map = new HashMap<Book, String>();
        map.put(new Book("java"),new String ("Development"));
        System.out.println(map.get(new Book("java")));
    }
}

Or:

public class TestDemo {
    public static void main(String [] args) {
        Map<String,Book> map = new HashMap<String, Book>();
        map.put(new String ("Development"),new Book("java"));
        System.out.println(map.get(new String("Development")));
    }
}
public class TestDemo {
    public static void main(String [] args) {
        Map<String,Book> map = new HashMap<String, Book>();
        map.put("Development",new Book("java"));
        System.out.println(map.get("Development"));
    }
}

summary

  • Map collections save data for more convenience and search, while Collection s save data for output
  • Map uses the Iterator interface to output steps:...
  • HashMap can save Null, Hashtable can not save null.
  • Can you repeat it or not? Once it happens, it will overwrite the original content (update the Value of Key)

Stack subclass

Stack means: stack operation; stack is a data structure of first-in, last-out; and Stack is a subclass of Vector.

public class Stack<E>
extends Vector<E>

Note: Stack is a Vector subclass, but it does not use the Vector method.

Stack stack operation:

  • Stack:
public E push(E item);
  • Out of the stack:
public E pop();
  • Implementing Stack-in and stack-out operations
public class TestDemo {
    public static void main(String [] args) {
        Stack<String> all = new Stack<String>();
        all.push("A");
        all.push("B");
        all.push("C");
        all.push("D");
        System.out.println(all.pop());
        System.out.println(all.pop());
        System.out.println(all.pop());
        System.out.println(all.pop());
    }
}

If all the data in the stack has been executed out of the stack and the pop operation continues to be executed out of the stack, an error is reported: empty stack exception (no data in the stack can be executed out of the stack)

Properties subclass

Collections Tool Class

  • Adding a set of data to a collection
public static <T> boolean addAll(Collection<E> c,......);
public class TestDemo {
    public static void main(String [] args) {
        List<String> all = new ArrayList<String>();
        Collections.addAll(all, "A","B","C","D");
        System.out.println(all);
    }
}

Collections Tool Class is responsible for providing an auxiliary operation method for Collection, the Collection Operating Interface.

Topics: PHP Java Python