Java collections (collection framework)

Java collection(Collection framework)

 

The java.util package that comes with the Java standard library provides collection classes. A Java collection is like a container, which can contain multiple objects (actually references to objects, but habitually called objects). With the addition of generics from Java 5, Java collections can remember the data types of objects in the container. Make the coding more concise and robust.

Java collections can be roughly divided into two systems, one is Collection and the other is Map.

Collection: Mainly composed of List, Set, and Queue interfaces. List represents an ordered and repeated collection; Set represents an unordered and non-repeatable collection; Java 5 adds a Queue system collection, which represents a kind of queue collection implementation.

Map: It represents a collection of key-value pairs with a mapping relationship.

[Java's collection design is very long, and it has undergone large-scale improvements in the middle, and some should not be used: Vector, Hashtable, Stack.

 

First introduce Collection, then introduce Map.

 

Collection

A Java collection is an object that can hold references to other objects. The collection interface declares the operations that can be performed on each type of collection. The Java collection framework provides programmers with pre-packaged data structures and algorithms to manipulate them.

The simple structure diagram of the relationship between interfaces and inherited classes under java.util.Collection is as follows:

 

 

The collection frame contains the following:

☆Interface: It is an abstract data type representing a collection. For example, Collection, List, Set, etc. The reason for defining multiple interfaces is to manipulate collection objects in different ways. Such as:

The Collection interface is the root interface of the Collection hierarchy. The List interface inherits from Collection and a List instance stores the elements of an ordered collection. The Set interface inherits from Collection and is a collection that does not contain repeated elements. The SortedSet interface is inherited from

☆Realization (class): It is the concrete realization of the collection interface. Essentially, they are reusable data structures. For example, the ArrayList class implements dynamic arrays. LinkedList implements a linked list. The TreeSet class uses the natural order of the elements to sort the elements.

☆ Algorithm: Some useful calculations performed by methods in objects that implement the collection interface, such as searching and sorting. These algorithms are called polymorphism, because the same method can have different implementations on similar interfaces.

 

List interface

List is the most basic kind of collection: it is an ordered list.

The behavior of List is almost the same as that of array: List is stored in the order of placing elements, and each element can determine its own position by index. The index of List is the same as that of array, starting from 0. However, using arrays is very inconvenient when adding and deleting elements. Therefore, in practical applications, an ordered list of elements needs to be added and deleted. ArrayList is the one we use most. ArrayList encapsulates the operations of adding and deleting, let us operate List similar to operating array, but do not care about how the internal elements move.

Another LinkedList also implements the List interface through a "linked list". In LinkedList, every element inside it points to the next element:

Comparison of ArrayList class and LinkedList class:

 

 

ArrayList

LinkedList

Get the specified element

high speed

Need to find elements from scratch

Add element to the end

high speed

high speed

Add/delete at specified location

Need to move elements

No need to move elements

Memory footprint

less

Larger

 

The construction methods of the ArrayList class are:

1. Constructor without parameters: ArrayList() constructs an empty list with an initial capacity of 10.

2. An int type constructor: ArrayList (int initialCapacity) constructs an empty list with the specified initial capacity initialCapacity.

3. A constructor for a specified collection: ArrayList (Collection<? extends E> c) constructs a list containing the elements of the specified collection, which are arranged in the order in which the collection's iterator returns them. The construction method is mainly to convert the implementation class of Collection to ArrayList.

 

Common methods of the ArrayList class

1. add(Object element): Add the specified element to the end of the list.

2. size(): Returns the number of elements in the list.

3. get(int index): Returns the element at the specified position in the list, index starts from 0.

4. add(int index, Object element): Insert the specified element at the specified position of the list.

5. set(int i, Object element): Replace the element at index i with element element and return the replaced element.

6. clear(): Remove all elements from the list.

7. isEmpty(): Judge whether the list contains elements, return true if it does not contain elements, otherwise return false.

8. contains(Object o): If the list contains the specified element, it returns true.

9. remove(int index): Remove the element at the specified position in the list and return the deleted element.

10. remove(Object o): Remove the specified element that appears for the first time in the collection, return true if the removal is successful, otherwise return false.

11. Iterator(): Returns an iterator that iterates over the elements of the list in the proper order.

 

Example 1. Examples of using ArrayList

import java.util. *;

import java.util. *;

public class ListTest {

    public static void main(String[] args) {

        ArrayList<Integer> myNumbers = new ArrayList<Integer>();

        myNumbers.add(10);

        myNumbers.add(15);

        myNumbers.add(20);

        myNumbers.add(25);

        for (int i : myNumbers) {

            System.out.println(i);

        }

    }

}

Run output:

10

15

20

25

 

Example 2: Example of traversing ArrayList

import java.util. *;

public class ListTestA{

 public static void main(String[] args) {

     List<String> list=new ArrayList<String>();

     list.add("Hello");

     list.add("World");

     list.add("HAHAHAHA");

     //The first traversal method uses For-Each to traverse the List

     for (String str: list) {//You can also rewrite the form for(int i=0;i<list.size();i++)

        System.out.println(str);

     }

 

     //The second kind of traversal is to traverse the linked list into array-related content

     String[] strArray=new String[list.size()];

     list.toArray(strArray);

     for(int i=0;i<strArray.length;i++) //here can also be rewritten as for(String str:strArray) this form

     {

        System.out.println(strArray[i]);

     }

    

    //The third type of traversal uses iterators for related traversals

    

     Iterator<String> ite=list.iterator();

     while(ite.hasNext())//Judging that there is a value after the next element

     {

         System.out.println(ite.next());

     }

 }

}

Three methods are used to traverse the ArrayList collection, the third method is to use the iterator method, this method does not have to worry about exceeding the length of the collection during the traversal process. Run output:

Hello

World

HAHAHAHA

Hello

World

HAHAHAHA

Hello

World

HAHAHAHA

 

 

LinkedList class

Linked list (Linked list) is a common basic data structure, a linear table, but it does not store data in a linear order, but stores the address of the next node in each node.

Linked lists can be divided into singly linked lists and doubly linked lists.

A singly linked list contains two values: the value of the current node and a link to the next node.

A doubly linked list has three integer values: numeric value, backward node link, and forward node link.

 

 

Java LinkedList (linked list) is similar to ArrayList and is a commonly used data container.

Compared with ArrayList, LinkedList's addition and deletion are more efficient for operations, while the search and modification operations are less efficient.

Use ArrayList in the following situations:

Frequently visit an element in the list.

Only need to add and delete elements at the end of the list.

Use LinkedList in the following situations:

You need to iterate through a loop to access certain elements in the list.

You need to frequently add and delete elements at the beginning, middle, and end of the list.

 

The construction methods of the LinkedList class are:

1. The default constructor

LinkedList()

2. Create a LinkedList to protect all elements in the Collection.

LinkedList(Collection<? extends E> c)

 

Common methods of the LinkedList class

1. add(element) adds a new node to the end of the linked list, the data in the node is the object specified by the parameter element

2. add( index, element) adds a new node to the specified position of the linked list, the data in the node is the object specified by the parameter element

3. addFirist( element) adds a new node to the head of the linked list. The data in this node is the object specified by the parameter element

4. addLast(element) adds a new node to the end of the linked list, the data in this node is the object specified by the parameter element

5. removeFirst() deletes the first node and returns the object in this node

6. removeLast() deletes the last node and returns the object in this node

7, remove (index) delete the node at the specified position

8. get( index) to get the node at the specified position

9. getFirst() to get the object of the first node of the linked list

10. getLast() gets the object of the last node of the linked list

11. indexOf(element) returns the position where the node object element first appears in the linked list, or -1 if there is no object of this node in the linked list

12. lastIndexOf(element) returns the last position of the node object element in the linked list, or -1 if there is no object of this node in the linked list

13. set( index, element) replaces the object in the node at the index position of the current linked list with the object specified by the parameter element, and returns the replaced object

14. size() returns the length of the linked list, that is, the number of nodes

15. contains(element) Determine whether the linked list node object contains element

 

Example 1. Examples of using the LinkeList class

import java.util. *;

public class LListTest

{

     public static void main(String[] args)

     {

          //Create an object of the LinkedList class

          LinkedList ll=new LinkedList();

          //Initialize the LinkedList object

          for(int i=0;i<5;i++)

          {

               ll.add(String.valueOf(i));

          }

          //Insert the LinkedList

          for(int i=5;i<10;i++)

          {

               ll.add(i,String.valueOf(10-i+5));

          }

          //Print LinkedList list

          System.out.println("Here is the result of LinkedList operation:");

          System.out.println(ll);

     }

}

Run output:

Here is the result of LinkedList operation:

[0, 1, 2, 3, 4, 10, 9, 8, 7, 6]

 

Example 2: Use the LinkeList class to set and delete elements

import java.util. *;

public class   LListTestA

{

    public static void main(String[] args)

    {

        //Create a LinkedList object

        LinkedList<String> liList = new LinkedList<String>(); //The parameters and return value must be String type

        for (int i = 0; i < 5; i++)

        {//Circularly add 5 string objects

            liList.add(String.valueOf(i));

        }

        System.out.println(liList); //Output the elements in the liList object

        System.out.println(liList.get(3)); //Output the element at position 3 of the liList object

        liList.set(3, "aaa"); //Set the element at position 3 to "555"

        System.out.println(liList);

        System.out.println(liList.peek()); //Find the head element of the list

        System.out.println(liList);

        System.out.println(liList.poll()); //Find the head element of the list and delete

        System.out.println(liList);

        System.out.println("The first element is" + liList.getFirst()); //Get the first element and output

        System.out.println("The last element is" + liList.getLast()); //Get the last element and output

    }

}

 

Run output:

[0, 1, 2, 3, 4]

3

[0, 1, 2, aaa, 4]

0

[0, 1, 2, aaa, 4]

0

[1, 2, aaa, 4]

The first element is 1

The last element is 4

 

Set interface

The biggest difference between the Set interface and the List interface is that there are no duplicate elements in the Set. Set is a very simple collection, and the objects in the set have no specific order. The Sorted interface has a sorting function, and the TreeSet class implements this interface; the HashSet class uses a hash algorithm to access the elements in the collection, and the access speed is relatively fast.

 

TreeSet class

TreeSet is an implementation class of the SortedSet interface. TreeSet can ensure that the elements are in a sorted state. It uses a red-black tree data structure to store set elements. TreeSet supports two sorting methods: natural sorting and custom sorting. Natural sorting is used by default.

 

The construction methods of the TreeSet class are:

1. The default constructor. Using this constructor, the elements in the TreeSet are arranged in natural order.

TreeSet()

2. The created TreeSet contains collection

TreeSet(Collection<? extends E> collection)

3. Specify the comparator of the TreeSet

TreeSet(Comparator<? super E> comparator)

4. The created TreeSet contains set

TreeSet(SortedSet<E> set)

 

Common methods of the TreeSet class

1. add (E e) If the specified element does not exist yet, add it to this set. More formally, if the set does not contain any elements, add the specified element to this set e2 Objects.equals(e, e2). If this set already contains the element, the call will leave the set unchanged and return false.

2. addAll (Collection <? extends E> c) adds all the elements in the specified collection to this collection.

3. remove (Object o) If it exists, remove the specified element from the collection. More formally, remove the element e so that Objects.equals(o, e), if this set contains such an element. Returns true whether this set contains the element (or equivalently, if this set is changed due to the call). (Once the call returns, the collection will not contain the element.)

4. size() returns the number of elements in this collection (its base).

5. isEmpty() true If this set does not contain any elements, it returns

6. E ceiling​(E e) returns the smallest element in this set that is greater than or equal to the given element, or null if there is no such element.

7. E floor(E e) returns the largest element in this set that is less than or equal to the given element, or null if there is no such element.

8. E lower​(E e) returns the largest element in this set strictly less than the given element, or null if there is no such element.

9, contains (Object o) true if this set contains the specified element, then return. More formally, return true if and only if the element e contained in this set makes Objects.equals(o, e).

 

Example 1. Examples of using the TreeSet class

import java.util. *;

public class TSetTest

{

     public static void main(String[] args)

     {

          //Created a TreeSet object

          TreeSet ts=new TreeSet();

          //Add strings with numbers 5, 6, 3, 2, 4 to the TreeSet object in turn

          ts.add(String.valueOf(5));

          ts.add(String.valueOf(6));

          ts.add(String.valueOf(3));

          ts.add(String.valueOf(2));

          ts.add(String.valueOf(4));

          //Removed the string "5" in the HashSet object

          ts.remove(String.valueOf(5));

          //Add the string with the content "1" to the HashSet object

          ts.add(String.valueOf(1));

          //Print out the contents of the TreeSet

          System.out.print("The result of the TreeSet operation is:");

          System.out.println(ts);

     }

}

Run output:

The result of the TreeSet operation is: [1, 2, 3, 4, 6]

 

Example 2. Examples of using the methods of the TreeSet class

import java.util. *;

public class TSetTestA

{

    public static void main(String[] args) throws Exception

     {

        TreeSet ts = new TreeSet(); //Create a TreeSet object

        for (int i = 5; i >= 0; i--)

        {//Add 5 integer objects in a loop

            ts.add(new Integer(i));

        }

        TreeSet anotherts = (TreeSet) ts.clone(); //Copy the TreeSet object

        Iterator it = anotherts.iterator();

        while (it.hasNext())

        {//Circularly output the elements in the it object

            System.out.println(it.next());

        }

        System.out.println("Create TreeSet Class");

        TreeSet s = new TreeSet(); //Create a TreeSet object

        s.add("aa"); //Add 4 string elements

        s.add("cc");

        s.add("dd");

        s.add("bb");

        Iterator its = s.iterator(); //Create an iterator object for the object s

        while (its.hasNext())

        {//Traverse the objects in the output s

            System.out.println(its.next());

        }

        System.out.println("The first element is:" + s.first()); //Output the first element in the s object

        System.out.println("The last element is:" + s.last()); //Output the last element in the s object

    }

}

 

Run output:

0

1

2

3

4

5

Create the TreeSet class

aa

bb

cc

dd

The first element is: aa

The last element is: dd

 

 

Queue interface

Queue is used to simulate the data structure of the queue. The queue usually refers to the "first in first out" (FIFO) container. The head of the queue is the element that has been stored in the queue for the longest time, and the tail of the queue is the element that has been stored in the queue for the shortest time. The new element is inserted (offer) at the end of the queue, and the poll operation returns the element at the head of the queue.

The Queue interface has a PriorityQueue implementation class. In addition, Queue also has a Deque interface. Deque represents a "double-ended queue". A double-ended queue can add and delete elements from both ends at the same time. Therefore, the implementation class of Deque can be used as a queue or a stack. To use, Java provides the implementation class ArrayDeque for Deque.

 

 

 

Map

In addition to collections, the java.util package also defines several Map interfaces and classes. What is stored in the Map are key/value pairs.

Simple structure diagram of the relationship between interfaces and inherited classes under java.util.Map:

 

 

 

 

appendix,

java collection https://blog.csdn.net/bingxuesiyang/category_8842042.html

Java collection framework https://www.runoob.com/java/java-collections.html

 

Guess you like

Origin blog.csdn.net/cnds123/article/details/112003418