Java set (1): Java set Overview

Source: Internet
Author: User

Java set (1): Java set Overview

1 Overview

Java provides a rich collection framework, which contains many interfaces, virtual classes, and implementation classes. These interfaces and classes provide rich functions to meet basic aggregation requirements. Is the overall structure of this framework:

As you can see, this framework is very big and surprising. The left part of the graph is the interface, the right part is the class, and the middle line represents the class on the right to implement the interfaces on the left. For example, if the AbstractList class implements the List interface, all subclasses inherited from the AbstractList class implement this interface. Also, if a class implements an interface, this class also implements all the parent interfaces of this interface. For example, if the TreeSet class implements the Deque interface, the TreeSet class also implements the Queue interface, Collection interface, and Iterable interface (the Interface Collection extends Iterable, which is not shown here ).

The red class in the figure indicates the Abstract class. Most Abstract classes start with Abstract, except Dictionary. The green class represents the legacy class, which existed at the beginning of Java.

2. Separation of interfaces and Implementations

Interfaces and implementations are separated in the Java Collection class library. The following uses the queue as an example.

The queue interface indicates that you can add elements at the end of the queue, delete elements in the queue header, and query the number of elements in the queue. That is, the elements in the queue use the queue according to the first-in-first-out elements.

If we design the queue interface, we may design it like this:

 

interface Queue
 
  {    void add(E element);    E remove();    int size();}
 
Three basic methods are provided here. This interface does not show how queues are implemented. Generally, queues can be implemented in two ways: loop array and linked list.

 

When using the cyclic array, you must specify the head and tail of the team. When using the linked list, you also need to give the head and tail:

 

class CircularArrayQueue
  
    implements Queue
   
    {    CircularArrayQueue(int capacity){...}    public void add(E element){...}    public E remove(){...}    private E[] elements;    private int head;    private int tail;}class LinkedListQueue
    
      implements Queue
     
      {    LinkedListQueue(){...}    public void add(E element){...}    public E remove(){...}    public int size(){...}    private Link head;    private Link tail;}
     
    
   
  
The above is just a simple queue we implemented by ourselves. The Java class library does not have these two classes. To use a Queue, you can use the Queue list class, which implements the Queue interface.

 

When using a queue in a program, once a set is built, you do not need to know which implementation is used. Therefore, it makes sense to use a specific class only when building a collection object. You can use the interface type to store the reference of the Set:

 

Queue
      
        employee=new CircularArrayQueue<>(100);employee.add(new Employee("Harry"));
      
Using this method, once you change your mind, you can easily use another implementation. You only need to modify a place of the program, that is, the place where the constructor is called. If the listqueue callback is a better choice, you can modify it as follows:

 

 

Queue
       
         employee=new LinkedListQueue<>();employee.add(new Employee("Harry"));
       
The interface itself does not provide a specific implementation method, so it cannot provide which implementation is more in line with the actual application. In this way, the programmer must select the implementation method. Many classes are implemented in the Java class library. Each class has its own characteristics and applicable scenarios. It may be better to select an implementation method for a specific feature, but it may also have to pay for another feature. To balance the cost of each performance, the class library users must be aware of it.

 

In, We can find many classes starting with Abstract in red. These classes are Abstract classes designed for the implementers of the class library. These classes implement some basic methods. If you want to implement your own Queue class, you will find it easier to extend the AbstractQueue analogy to implement the Queue interface.

3. Set interfaces and iterator interfaces in the Java class library

In the Java class library, the basic interface of the Collection class is the Collection interface. This interface has the following two methods:

 

boolean add(E element);Iterator
        
          iterator();
        
Of course, there are other methods besides these two methods, which will be introduced later.

 

The add method is used to add elements to a set. If the added element does change the set, true is returned. If the set does not change, false is returned.

The iterator method is used to return an object that implements the Iterator interface. You can use this iterator object to access the elements in the Set in sequence.

Next we will introduce the important iterator in the Java class library.

The Iterator interface has three methods:

 

public interface Iterator
         
          {    E next();    boolean hasNext();    void remove();}
         
By calling the next method repeatedly, you can access each element in the set one by one. However, if the end of the set is reached, the next method throws a NoSuchElementException exception. Therefore, you should call the hasNext method before calling the next method. If the iterator object has multiple elements for access, this method returns true. Therefore, you can use the following method to access all elements in the Set:

 

 

Collection
          
            c=...;Iterator
           
             it=c.iterator();while(it.hasNext()){    String element=it.next();    do something with element}
           
          
From Jave SE 5.0, you can also use the for each loop to access all elements in the Set:

 

 

for(String element : c){    do something with element}
The compiler only translates this for each loop into a loop with an iterator.

 

The for each loop can work with any object that implements the Iterable interface. This interface only contains one method:

 

public interface Iterable
            
             {    Iterator
             
               iterator();}
             
            
The Collection interface extends the Iterable interface, so any set in the standard library can use the for each loop.

 

Note that the order in which elements are accessed depends on the type of the set. If you iterate on the ArrayList, The iterator starts from index 0, each iteration, and the index value is increased by 1. However, if you access elements in a HashSet, each element will appear in a random order. Although we can determine that all elements can be traversed during the iteration process, we cannot predict the order in which elements are accessed.

The iterator in the Java Collection class library is conceptually different from the iterator in other class libraries. The C ++ iterator is modeled based on the array index. Given such an iterator, you can view the elements at the specified position, just as you can view array element a [I] by knowing array index I. You can move the iterator forward to a position without searching for elements. This is the same as moving the array index forward through I ++ without performing the search operation. However, this is not the case for Java iterators. Search operations and location changes are closely linked. The only way to find an element is to call next. While performing the search operation, the iterator moves forward.

That is, the iterator can be viewed as a position between two elements. The next operation will change this position. However, when next is called, The iterator goes beyond the next element and returns the reference of the element that has just been crossed.

The remove Method of the Iterator interface is used to delete the elements returned when the next method is called last time. That is to say, the remove operation and next operation are dependent. If the next method is not called and the remove Method is invalid, an IllegalStateException exception will be thrown. The first element in the set is deleted as follows:

 

Iterator
              
                it=c.iterator();it.next();it.remove();
              
If two adjacent elements are deleted, the following method is incorrect:

 

 

it.remove();it.remove();
You must first call the next method to overwrite the elements to be deleted:

 

 

it.remove();it.next();it.remove();
There is an inappropriate metaphor for the iterator as the cursor:

 

 

Collection
               
                 c=ArrayList<>();c.add("a");c.add("b");c.add("c");Iterator
                
                  it=c.iterator();
                
               
In this case, the iterator position is as follows:

 

| A B c

When the next method is called, The cursor will move behind and then return the elements that have just been crossed:

 

it.next();
The iterator position is as follows:

 

A | B c

And return Element.

If you want to delete an element, the deletion behavior is like the Backspace operation. Delete the elements following the cursor (before right:

 

it.remove();
The iterator position is as follows:

 

| B c

Unlike the backward key, if there are still elements behind the iterator, the next method cannot be deleted without being called.

Because both the Collection interface and Iterator interface are generic interfaces, You can compile a practical method to operate on any set type. In fact, there are many methods in the Collection interface:

 

public interface java.util.Collection
                 
                   extends java.lang.Iterable
                  
                    {  public abstract int size();  public abstract boolean isEmpty();  public abstract boolean contains(java.lang.Object);  public abstract java.util.Iterator
                   
                     iterator();  public abstract java.lang.Object[] toArray();  public abstract 
                    
                      T[] toArray(T[]);  public abstract boolean add(E);  public abstract boolean remove(java.lang.Object);  public abstract boolean containsAll(java.util.Collection);  public abstract boolean addAll(java.util.Collection);  public abstract boolean removeAll(java.util.Collection);  public boolean removeIf(java.util.function.Predicate);  public abstract boolean retainAll(java.util.Collection);  public abstract void clear();  public abstract boolean equals(java.lang.Object);  public abstract int hashCode();  public java.util.Spliterator
                     
                       spliterator();  public java.util.stream.Stream
                      
                        stream(); public java.util.stream.Stream
                       
                         parallelStream();}
                       
                      
                     
                    
                   
                  
                 
There are many methods with clear meanings. I will not explain them too much here.

 

Of course, it would be annoying to implement these routine methods for every class implementing the Collection interface. To make it easier for the implementer to implement this interface, the Java class library provides a AbstractCollection class, which provides some routine methods, A specific collection class can expand the AbstractCollection class without implementing all the routine methods, and can overwrite the methods in it.

4. interfaces in the Java class library

All interfaces in the Java class library are provided:

Collection and Map are two main interfaces of the Collection framework. All Collection classes implement one of these two interfaces. The Iterator interface and ListIterator interface are the Iterator interfaces, while the ListIterator interface provides richer operations, which will be described in the List. The RandomAccess interface is a label interface, that is, this interface does not have any methods, but you can use this interface to mark a class and check whether a class supports random access.

In the subsequent introduction, we will detail the methods and usage of these interfaces.

5. classes in the Java class library

The following are all implementation classes in the Java Class Library:

Abstract classes are highlighted in red. It can be clearly divided into two parts: a Collection and a Map ).

These are common classes, and some specialized classes are added, such as EnumSet, LinkedHashSet, EnumMap, LinkedHashMap, IdentityHashMap, and WeakHashMap. They have 14 categories in total. Their features are as follows:

 

Specific set in the Java Library
Set Type Description
ArrayList An index sequence that can be dynamically increased or scaled
Shortlist An ordered sequence in which efficient insert and delete operations can be performed anywhere.
ArrayDeque A dual-end queue implemented by cyclic Array
HashSet An unordered set with no repeated Elements
TreeSet An ordered set
EnumSet A set that contains enumerated values.
LinkedHashSet A set that remembers the sequence of element insertion.
PriorityQueue A set that allows efficient deletion of minimum elements
HashMap A Data Structure that stores key/value associations.
TreeMap A ing table with sorted key values
EnumMap A key value belongs to an enumeration type ing table.
LinkedHashMap A ing table that remembers the order in which key-value items are added
WeakHashMap A ing table whose values are useless and can be recycled by the Garbage Collector
IdentityHashMap A ing table that uses = instead of equals to compare key values

For ordered disorder, element duplication, and element duplication, the features are summarized as follows. Note that for Map, check whether the key value can be repeated:

6. More

In the post-order analysis, we will introduce these specific classes and sets:

2. Java set (2): List

3. Java Set (3): Set

4. Java set (4): Queue

5. Java Set (5): dedicated Set and dedicated Map

6. Java set (6): Java set framework

7. Java set (7): algorithms and legacy classes in the Java set

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.