Make writing a habit together! This is the 14th day of my participation in the “Gold Digging Day New Plan · April More Text Challenge”. Click here for more details.


⭐️ ⭐️

This article introduces you to the basics of Java — collections framework. It begins with a formal introduction to data structures. In order to learn more about what a Java Collection box looks like, this article introduces you to how to use the Collection and Map interfaces.

📒 blog homepage: not seen flower smell blog homepage 🎉 welcome to pay attention to 🔎 like 👍 collect 🎉 🎉 message 📒 📆 Nuggets debut: 🌴 April 15, 2022 🌴 ✉️ Perseverance and hard work will be exchanged for poetry and distance! 💭 refer to books: 📚 “Java programming ideas”, 📚 “Java core technology” 💬 refer to online programming website: 📚 niuke.com SILVER force to deduct the code cloud of the blogger gitee, usually the program code written by the blogger are in it. Github of the blogger, the program code written by the ordinary blogger is in it. 🍭 author level is very limited, if you find mistakes, be sure to inform the author in time! Thank you, thank you!

1. First look at the collection framework

The collection framework is described in the official documentation as a unified framework for representing and manipulating collections. All collections frameworks contain the following:

Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be manipulated independently of the details they represent. In object-oriented languages, interfaces often form hierarchies.

Implementations: These are concrete implementations of the collection interface. In essence, they are reusable data structures.

Algorithms: These are methods that perform useful computations, such as searching and sorting, on objects that implement the collection interface. These algorithms are said to be polymorphic: that is, the same method can be used for many different implementations of the appropriate collection interface. Algorithms are essentially reusable features.

Aside from the Java collections framework, the best-known examples are the C++ standard template library (STL) and Smalltalk’s collection hierarchy. Reference link: Introduction to the official collections framework

The Java Collection Framework, also known as a container, is a set of interfaces and their implementation classes defined under the java.util package. Generally speaking, a collection framework is composed of many interfaces and classes connected by a series of inheritance and extension relationships to form a “network”, called a framework. These interfaces and classes provide a variety of ways and methods of the data, including data organization is the data structure, provides the method contains the add or delete of data structure change and sorting method, these methods can be done by different algorithms, such as sorting a bubble, selection, insertion, hill, barrels, fast, heap, count sorting algorithm and so on.

Simply put, a collection framework is made up of interfaces, abstract classes, and implementation classes that implement data structures.

In Java, the collection framework looks something like this:

According to this diagram, the Iterable interface is mainly used to use the enhanced for-each loop, so the data structures implementing the Iterable interface can be iterated using for-each, such as List for linear structures, Queue for queues, Set for collections, The above three interfaces all extend the interface, so these types of data structures can use the for-each loop, but the Map interface is a separate key-value pair, and this kind of data structure cannot use the for-each loop. The Collection interface is actually used to manage objects. According to the figure, the interface is implemented by all data structures except key-value pairs. Therefore, the interface can manage various data structure objects, which are also called elements.

For implementation classes, different data structures are formed according to different interfaces implemented, such asArrayList(Sequence table),LinkedList(Lists and queues),Stack(stack), etc., basically the collection framework contains most of j’s simple data structures, which will be covered in future posts. In addition to these, the collections framework provides a number of tools, such asThe iterator.The comparatorAnd so on.

This is what the Java Collections framework looks like, and how to use it and implement some of the data structures will be covered in future posts.

2.Collection

We have already seen the general appearance of Java collections framework, believe that you have a certain understanding of collections, while the iron is hot, to learn the use of Collection framework!

Most data structures implement this interface (except for key-value pairs), which means that the Collection interface can accept references from multiple implementation classes. Collections are often used to manage objects, and implementation classes can use methods in this interface, but the Collection interface is generally not used much. It usually uses its subinterfaces List, Queue, Set, etc.

Learn more about collections: Official Collection notes

Instead of enumerating all the methods in this interface, here are some common ones.

methods instructions
boolean add(E e) Insert the element e into the set
void clear() Deletes all elements in the collection
boolean isEmpty() Determine whether the set does not have any elements, commonly known as empty set
boolean remove(Object e) If the element e appears in the collection, remove one of them
int size() Returns the number of elements in the collection
Object[] toArray() Returns an array containing all the elements of the collection

In Java, most simple data structure classes implement the Collection interface. Take ArrayList for example.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;

public class Test {
    public static void main(String[] args) {
        Collection<Integer> coll = new ArrayList<>();
        // Add elements
        coll.add(115);
        coll.add(2022);
        coll.add(4848);
        //ArrayList implements the toString method, so you can output the entire collection of elements using reference names
        System.out.println(coll);
        // Get the number of elements
        System.out.println(coll.size());
        // Return an array of type Object[]
        Object[] arr = coll.toArray();
        System.out.println(Arrays.toString(arr));
        // Determine and delete element e
        System.out.println(coll.remove(4848));
        System.out.println(coll);
        // Clear the collection
        coll.clear();
        System.out.println(coll);
        // Check whether the set is emptySystem.out.println(coll.isEmpty()); }}Copy the code

Running results:

3.Map

The Map interface can accept a reference to a collection object composed of key and value pairs. Let’s introduce some common methods in the Map interface. A key-value pair is onekeyCorresponds to aval. A collection of key-value pairs is called a Map, and other partial languages are called dictionaries.

For more information, see the official Map description: Map official description

Common methods:

methods instructions
V get(Object k) Finds the corresponding val based on the specified key
V getOrDefault(Object k, V defaultValue) Select val (key, val) from val (key, val)
V put(K key, V value) Puts the specified key-val into the Map
boolean containsKey(Object key) Check whether the key is included
boolean containsValue(Object value) Check whether value is included
Set<Map.Entry<K, V>> entrySet() Returns all key-value pairs as a collection
boolean isEmpty() Check whether the map is empty
int size() Returns the number of key-value pairs

Note that the V and K in the above methods stand for generics, but you only need to know that generics can be used to pass types, which will be covered in future posts. The example uses a HashMap, which is a key-value pair implemented using a hash table.

Insert the key-value pair — put method

import java.util.HashMap;
import java.util.Map;

public class TestMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        // Insert key-value pairs
        map.put("1024"."Programmer day");
        map.put("New Year's Day"."Spring Festival");
        map.put("The first of January".New Year's Day); System.out.println(map); }}Copy the code

We’ll see that the order of the key-value pairs is not the same as the order in which we inserted them becauseHashMapIt’s using hash tables. YeahkeyHash mapping is stored to the hash table location of the corresponding index, so the order of insertion does not determine the order in which the key-value pair is stored.

Val — get, getOrDefault = val — get, getOrDefault

import java.util.HashMap;
import java.util.Map;

public class TestMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        // Insert key-value pairs
        map.put("1024"."Programmer day");
        map.put("New Year's Day"."Spring Festival");
        map.put("The first of January".New Year's Day);
        // Find val by key
        System.out.println(map.get("1024"));
        System.out.println(map.getOrDefault("The fifteenth day of the first month".Lantern Festival)); }}Copy the code

Check whether it containsKey or val — containsKey, containsValue

import java.util.HashMap;
import java.util.Map;

public class TestMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        // Insert key-value pairs
        map.put("1024"."Programmer day");
        map.put("New Year's Day"."Spring Festival");
        map.put("The first of January".New Year's Day);
        // Whether to include key
        System.out.println(map.containsKey("1024"));//true
        System.out.println(map.containsKey("The fifteenth day of the first month"));//false
        // Whether to include val
        System.out.println(map.containsValue("Spring Festival"));//true
        System.out.println(map.containsValue(Lantern Festival));//false}}Copy the code

Convert all key-value pairs into collections — entrySet()

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class TestMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        // Insert key-value pairs
        map.put("1024"."Programmer day");
        map.put("New Year's Day"."Spring Festival");
        map.put("The first of January".New Year's Day);
        // set all key values
        Set<Map.Entry<String, String>> set = map.entrySet();
        for(Map.Entry<String, String> kv: set) {
            System.out.println("Date:" + kv.getKey() + "Festival:"+ kv.getValue()); }}}Copy the code

Get the number of key-value pairs in the Map and determine whether the Map isEmpty — size, isEmpty

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class TestMap {
    public static void main(String[] args) {
        Map<String, String> map = new HashMap<>();
        // Insert key-value pairs
        map.put("1024"."Programmer day");
        map.put("New Year's Day"."Spring Festival");
        map.put("The first of January".New Year's Day);
        // Get the number of key-value pairs and determine whether the map is emptySystem.out.println(map.size()); System.out.println(map.isEmpty()); }}Copy the code

Well, that’s the end of this article. See you next time!