List interface related knowledge - ArrayList data structure - Java - Detail Magic (estimated tens of thousands of words)

Posted by veronicabend on Wed, 08 Dec 2021 18:00:56 +0100

Introduction of generics

Generics in the last article Collection framework is the underlying data structure It has been lowered and is ready for use.
There are two concepts to understand before you start

  1. First, we know a premise in learning polymorphism that references to base classes can point to objects in subclasses.
  2. Second, we also know that Object is the ancestor class of all classes in java.

Implement a generic sequential table (direct practice)

The functionality of the Sequence Table is not the focus. Here we're just going to get a rough look at the functionality of the Sequence Table, focusing on generics

Prepare work, I believe everyone can understand.

class MyArrayList{
    private int[] elem;// Create Array
    private int usedSize;// Number of valid elements

    public  MyArrayList(){// Construction method
        this.elem = new int[10];// Default array initial capacity is 10
    }
    public void add(int val){// Add Elements
        this.elem[usedSize] = val;
    }
    public int get(int pos){// Get the element at the specified location
        return  this.elem[pos];
    }
}
public class Test {
}

However, this code is not generic and can only store one data type (int).

Start pulling


Let's talk about output again

Pull on some details again

summary

1. Generics are a mechanism that works during compilation, i.e. there is no concept of generics during run time.
2. Generic code works during runtime, as we mentioned above, using Object (which is not very accurate here and will be explained later).
3. Generics are introduced to address the generality of some containers, algorithms, and other code, and can be type checked during compilation.
4. Generics make use of Object s as ancestor classes of all classes, and references to parent classes can point to specific subclass objects and work.
5. Generics are a compilation-time mechanism, that is, MyArrayList and MyArrayList are types at run time.
6. Generics are a legal syntax in java, marked by angle brackets <>

Wrapper Class

Object references can point to any type of object, with the exception that eight basic data types are not objects. Is that not what the generic mechanism just described?
Failed?

Actually, this is also true. To solve this problem, java introduces a special class, which is the wrapper class of the eight basic data types, and uses it
In, values such as int are wrapped in an object.

Direct correspondence between basic data types and packaging classes

Basically the first letter of the type is uppercase, except Integer and Character

Basic data typesPackaging Class
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
charCharacter
booleanBoolean

Significance of the Existence of Packaging Classes

When we need to convert one type of data into another, we need to do so in some way.
Packaging classes are the masters of these functions, including a variety of type conversion methods and other functions.

Actual Warfare (about converting a string type to integer data)

"Boxing/packing" and "unbosxing/unpacking" of packing class

Boxing/Packaging: is to change simple type data into wrapper type data
Unpacking/unpacking: is to change the wrapper class type data to simple type data

Let me give you an interview here

ArrayList and Sequential Table

Explain while practicing

Padding before actual battle


The small window shows that the List interface also implements several interfaces, or the parent interface of the List interface

The reason you've been taught to pop up this box is to add a few more explanations. Let's take a look at the ArrayLis chart

1. ArrayList implements the RandomAccess interface, indicating that ArrayList supports random access
2. ArrayList implements the Cloneable interface, indicating that ArrayList is Cloneable
3. ArrayList implements the Serializable interface, indicating that ArrayList supports serialization (serialization: converting an object to a string)
4. Unlike Vector, ArrayList is not thread-safe and can be used with a single thread, or Vector can be selected with multiple threads or
CopyOnWriteArrayList
5. The bottom of the ArrayList is a continuous space that can be dynamically expanded and is a dynamic type of sequential table

When using a class written by any idea compiler, it's important to first look at how this class is constructed

Three Printing Methods for ArrayList


Referenceable Sequence Table and Chain Table-Sequence Table Part To learn about the common functions of ArrayList, and Closed Framework is the underlying data structure Learn about the basic properties and functions of common interfaces.

Extension (Iterator Printing)


ArrayList Basic Functions Demo

Add and addAll, add element functions

public class TestDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");// Add List Element
        System.out.println(list);
        System.out.println("===============");
        list.add(1,"g");// Add elements to the List at specified locations
        System.out.println(list);
        System.out.println("========");
        List<String> list1 = new ArrayList<>();
        list1.add("x");
        list1.add("y");
        list.addAll(list1);// Add a list1 as a whole to the list
        System.out.println(list);
    }
}

Appendix

remove - Deletes the element with the specified subscript, and the return value is Delete Element

Appendix (remove internal implementation)

remove - Output first specified data from left to right - Return value is Boolean type

Internal implementation of the remove function is illustrated

get - Exchanges the element at the specified subscript position

Appendix (inside get method)


Before removing elements from elementData, force the type.

set - Sets the specified subscript element to the specified data (which can be understood as updating the specified subscript element) - Returns the old element

set internal drawings

clear - Empty the elements in the order table - No return value

clear internal implementation drawings

contains determines whether the specified data is in a linear table - the return value is a Boolean type

Internal implementation of contains Attached

indexOf - Returns the position of the first occurrence of the specified data in a linear table, corresponding to the subscript

indexOf internal implementation attached


lastIndexOf - Returns the last element subscript in a linear table equal to the specified element



Last IndexOf Internal Implementation Attached

subList - Truncate Partial Linear Table Data - Return Value is List < E > Type

Internal implementation of subList Attached

Extension mechanism for ArrayList

To see if the following code is defective

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        list.add(i);
    }
}

First of all, we think this code is flawless, but since the array at the bottom of the ArrayList is of a certain size, there must be expansion involved in storing the array.
As we mentioned earlier, there are three ways to use an ArrayList, which is now parameterless, meaning that the array at the bottom of the ArrayList has an initial capacity of zero. Then the first question arises: Since the capacity of an array is zero, how can it still store data?
Second question: Assuming that the array initialization capacity is 10 and exceeds 10, the capacity needs to be expanded. What is the mechanism by which an ArrayList expands when it stores data and implicitly expands when it executes at the bottom of the code?

Next come tear it by hand with me

Simulate the implementation of ArrayList, this time compared to the last blog post Sequence Table and Chain Table-Sequence Table Part More detailed.

Create a new MyArrayList class in which we only need to write down the two most important properties

Then there are the construction methods: two construction methods with and without parameters

Let's start with the nonparametric

Construction method with parameters

&ensp;

What to write next, follow this table to implement its basic functions. (If you can't understand it, you can turn it upside down and see it in front of you.)

// E is a data type

Methodexplain
boolean add(E e)Tail e
void add(int index,E element)Insert e into index position
boolean addAll(Collection<? extends E> c)Interpolate elements in c (all elements in one order table, into another order table)
E remove(int index)Remove index position element
boolean remove(Object o)Delete first o encountered
E get(int index)Get subscript index position element
E set(int index,Eelement)Replace an element labeled index with an element
void clear()empty
boolean contains(Object o)Determining whether o is in a linear table
int indexOf(Object o)Return the subscript of the first o from left to right
int lastIndexOf(Object o)Returns the subscript of the last o (returns the subscript of the first O from right to left)
List subList(int fromIndex,int tolndex)Intercept section list

add function

&ensp;

The function of add index is simple, because the way it's supported is now almost done

Effect Chart for add Two Usages

remove function - delete the first specified element encountered

remove function - delete index location element

get - Gets the specified subscript position element

set - Replaces the specified subscript element with the specified data

clear - Empty

contains - Determines whether a specified element is in a linear table

IndexOf and lastIndexOf, move the source code directly (note that indexOf was written earlier (just change private s to public), move lastIndexOf directly)


Design sketch

Summary:

The basic functionality is implemented, except for the subList, which involves reflex knowledge that bloggers haven't yet learned. Write it later.
And did you find it? In fact, you want to simulate the function of the sequence table, the best teacher is the original. In the future, when you are learning a data structure, first look at its source code, which will help you understand and master it.

In fact, this time it's a simulation, just a slight loss of detail. We haven't handled type conversion and toString method from writing yet, because I still have a writing problem and don't know how to solve it, so I wrote one according to my own ideas, the original toString still has some places that I don't understand thoroughly.

ArrayList Practice Case - Poker

Purpose:
1. Construct a deck of playing cards
2. Uncover
No rules for playing cards, unless you want me to play four.

Characteristics of playing cards


1. Points
2. Colors

Note: Our poker set does not include King and King.

According to the characteristics of playing cards, a class is abstracted.

Make a card

Make a deck of cards

Shuffle - (Ask such cards, blossom, who dares to go? Who goes and who dies.)

Deal/unveil and deal

Suppose there are three people playing the same suit, that is, each person will get five cards in his hand.

At the end of the article, there's a poker program attached (get and set are not used, you can't write them, I'm just used to triple play)

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

class Card{
    private int point;
    private String flowerColor;

    public Card(int point, String flowerColor) {
        this.point = point;
        this.flowerColor = flowerColor;
    }

    public int getPoint() {
        return point;
    }

    public void setPoint(int point) {
        this.point = point;
    }

    public String getFlowerColor() {
        return flowerColor;
    }

    public void setFlowerColor(String flowerColor) {
        this.flowerColor = flowerColor;
    }

    @Override
    public String toString() {
        return "{  " +flowerColor +" "+point+" }";
    }
}

public class PlayingCard {
    // Define the suit of playing cards
    private static final String[] flowerColors = {"♥","♠","♦","♣"};

    // Create a set of Poker
    public  static List<Card> newCard() {
        ArrayList<Card> cards = new ArrayList<>();
        for (int i = 0; i < 4; i++) {// 4 Colors
            for (int j = 1; j <= 13; j++) {// A total of 13 points from tip to k
                cards.add(new Card(j,flowerColors[i]));
            }
        }
        return cards;
    }

    // Shuffle the cards
    public static void shuffle(List<Card> list){
        // Number of cards is 52, array subscript is 51
        // Starting with the last card, swap positions randomly with itself or with any card in front of itself.
        // This is more efficient for interchangeability than disrupting the order from the start.
        for (int i = list.size()-1; i >0 ; i--) {
            // Random is a class that generates random numbers
            Random random = new Random();

            // The nextInt() method is called with Random's reference random.
            // random.nextInt() method that randomly generates values in parentheses from 0 to
            int rand = random.nextInt(i);

            // Throw the i card, the subscript of any card with itself or in front of itself, to the swap method
            // Let it swap places
            swap(list,i,rand);
        }
    }
    // Interactive shuffling mode
    private static void swap(List<Card> list,int i,int j){
        // We are now object-oriented, and although the ArrayList is an array at the bottom, we need to use methods to manipulate the elements of the array
        // Not directly like arrays

        // Card tmp = list[i];
        Card tmp = list.get(i);// Gets the element corresponding to the subscript in the order table

        // list[i] = list[j];
        list.set(i,list.get(j));// Assign the element with the j subscript to the element with the i subscript,

        // list[j] = tmp;
        list.set(j,tmp);
    }

    public static void main(String[] args) {
        System.out.println("======A pair of cards bought for disassembly==========");
        List<Card> list = newCard();
        System.out.println(list);
        System.out.println("======== Shuffle the cards =========");
        shuffle(list);
        System.out.println(list);
        System.out.println("======== Deal cards, 3 people in turn, 5 cards per person=========");

        ArrayList<ArrayList<Card>> player = new ArrayList<>();
        // This line of code is a two-dimensional array.
        // First we have a player, and each element of the player is of the ArrayList <Card>type.
        // That is, each element is a sequential table or a one-dimensional array.
        // You can also understand that the first ArrayList is the address or array that records the player's position/order table
        // The second ArrayList is the case of each player's hand/the elements of the array/the bottom elements of the order table.
        //  You can think of the player as a card table and wait for three players to enter.

        // Three-player deck
        ArrayList<Card> playerOne = new ArrayList<>();
        ArrayList<Card> playerTwo = new ArrayList<>();
        ArrayList<Card> playerThree = new ArrayList<>();
        // Load information about three players into the player
        player.add(playerOne);
        player.add(playerTwo);
        player.add(playerThree);
        for (int i = 0; i < 5; i++) {// Deal 5 rounds
            for (int j = 0; j < 3; j++) {// Everyone turns, and eventually each person gets five cards
                Card card = list.remove(0);
                player.get(j).add(card);
            }
        }

        // Print everyone's hand
        System.out.println("playerOne Hand cards:"+ playerOne);
        System.out.println("playerTwo Hand cards:"+playerTwo);
        System.out.println("playerThree Hand cards:"+playerThree);
        System.out.println("list Remaining cards:"+list);
    }

//    public static void main1(String[] args) {
//        Card card = new Card(3,"♠");
//        System.out.println(card);
//    }
}

Topics: Java data structure list