java note 7 array and storage structure

Posted by amansabharwal on Wed, 02 Mar 2022 19:11:57 +0100

VII Arrays and data storage

Learning objectives:

1. Array definition

An array is an ordered collection of data of the same type. Among them, each data is called an element, and each element can access them through an index (subscript).

Four basic features of arrays:

  1. The length is determined. Once an array is created, its size cannot be changed.
  2. The type of its element must be the same type, and mixed types are not allowed.
  3. Array types can be any data type, including basic types and reference types.
  4. Array variables belong to the reference type. Array is also an object. The elements in the array are equivalent to the attributes of the object!

2. Create array initialization

Declaration method of array (taking one-dimensional array as an example)

type[ ] arr_name; //Mode 1
type arr_name[ ]; //Mode 2

Note:

  • No object is instantiated at the time of declaration. The JVM allocates space only when the array object is instantiated, which is related to the length.
  • When declaring an array, no array is actually created.
  • To construct an array, the length must be specified.

[example] create a basic type one-dimensional array

public class test01 {
    public static void main(String[] args) {
        int[] s;//Declaration array;
        s=new int[10];//Space the array separately;
        for(int i=0;i<10;i++){
            s[i]=2*i+1;//Assign values to array elements; Arrays are objects. The elements in the array are the attributes of the object
            System.out.println(s[i]);
        }
    }
}

[create one-dimensional reference type] example

class Man{
    private int age;
    private int id;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public void setId(int id) {
        this.id = id;
    }

    public Man(int id, int age) {
        super();
        this.age = age;
        this.id = id;

    }
}
public class test02 {
    public static void main(String[ ] args) {
        Man[ ] mans; //Declare an array of reference types;
        mans = new Man[10]; //Allocate space to the reference type array;
        Man m1 = new Man(1,11);
        Man m2 = new Man(2,22);
        mans[0]=m1;//Assign a value to the element of the reference type array; Assign an address to it
        mans[1]=m2;//Assign a value to the element of the reference type array; Assign an address to it
        System.out.println(mans[0].getAge());
        System.out.println(mans[1]);
        System.out.println(m2);
    }
}

Operation results:

3. Initialization

There are three initialization methods: static initialization and dynamic initialization.

1. Static initialization

In addition to using the new keyword to generate an array, you can also directly allocate space and assign values to the array elements while defining the array.

int [ ] a = { 1, 2, 3 };// Static initialization of basic type array;
Man[ ] mans = { new Man(1, 1), new Man(2, 2) };// Statically initialize the reference type array;

2. Dynamic initialization

Array definition is separated from the operation of allocating space and assigning values to array elements.

int[ ] a1 = new int[2];//Dynamically initialize the array and allocate space first;
a1[0]=1;//Assign values to array elements;
a1[1]=2;//Assign values to array elements;

3. Default initialization of array

Array is an object, and its elements are equivalent to the attributes of the object; Each element is also initialized by default as an attribute.

int a2[ ] = new int[2]; // Default: 0,0
boolean[ ] b = new boolean[2]; // Default value: false,false
String[ ] s = new String[2]; // Default: null, null

4. Common operations of array

Traversal and copy

  1. Traversal refers to "traversing all elements of an array through a loop".

  2. Copy refers to copying the contents of one array to another

    Note: in essence, the expansion of container is "copy of array".

1. Array traversal

Legal range of array element subscript: [0, length-1]. We can traverse the elements in the array through subscripts. When traversing, we can read the value of the element or modify the value of the element.

[example] use a loop to initialize and traverse an array

public class test03 {
    public static void main(String[] args) {
        int[] a=new int[4];
        //Initializes the value of an array element
        for(int i=0;i<a.length;i++){
            a[i]=100*i;
        }
        //Read the value of the element
        for(int i=0;i<a.length;i++){
            System.out.println(a[i]);
        }
    }
}

Execution result:

For each loop

For each is specifically used to read all elements in an array or container.

[example] using enhanced for loop to traverse array

public class test03 {
    public static void main(String[] args) {
        int[] a=new int[4];
        //Initializes the value of an array element
        for(int i=0;i<a.length;i++){
            a[i]=100*i;
        }
        for(int t:a){
            System.out.println(t);
        }
    }
}

The implementation results are the same as above

public class Test03 {
	public static void main(String[ ] args) {
		String[ ] ss = { "aa", "bbb", "ccc", "ddd" };
		for (String temp : ss) {
			System.out.println(temp);
		} 
    }
}

Execution result:

be careful:

  1. For each enhanced for loop can only read and cannot modify the value of an element in the array when traversing the array;
  2. For each is only applicable to traversal and does not involve operations related to indexes (subscripts).

2. Copy of array

System.arraycopy(object src,int srcpos,object dest,int destpos,int length)

This method can assign the elements in src array to the elements of dest array, where srcpos specifies the first few elements of src array, and the length parameter specifies how many elements of src array are assigned to the elements of dest array.

[example] copy of array

public class test04 {
    public static void main(String[] args) {
        String[] s={"Ali","Shang Xuetang","JD.COM","Sohu","Netease"};
        String[] sBak=new String[6];
        System.arraycopy(s,0,sBak,0,s.length);
        for(int i=0;i<sBak.length;i++){
            System.out.println(sBak[i]+"\t");
        }
    }
}

3.java.util.Arrays class

The Arrays class contains common array operations such as sorting, finding, filling, and printing content.

Some operations using the Arrays class

import java.util.Arrays;

public class test05 {
    public static void main(String[] args) {
        //Use the Arrays class to output the elements in the array
        int[] a={1,2};
        System.out.println(a); //Print the value of array reference;
        System.out.println(Arrays.toString(a));  //Print the values of array elements;
 // Note: Arrays here to. The string () fan method is a static method of the Arrays class, not the toString() method of Object.
        System.out.println(" ");

        //Use the Arrays class to sort array elements
        int[] b={1,2,3,7,6,5,4};
        System.out.println(Arrays.toString(b));
        Arrays.sort(b);
        System.out.println(Arrays.toString(b));
        System.out.println(" ");

        //Use the Arrays class to realize the dichotomy search method
        int[] c={1,2,3,7,6,5,4,3,2,1};
        System.out.println(Arrays.toString(c));
        Arrays.sort(c);  //When using dichotomy search, you must sort the array first;
        System.out.println(Arrays.toString(c));
        //Returns the new index position after sorting. If it is not found, it returns a negative number;
        System.out.println("Index of this element:"+Arrays.binarySearch(c,6));
        System.out.println(" ");

        //Use the Arrays class to populate the array
        int[] d={1,5,4,2,3};
        System.out.println(Arrays.toString(d));
        Arrays.fill(d,2,4,100);  //Replace the elements of 2 to 4 indexes with 100; (excluding 4)
        System.out.println(Arrays.toString(d));
    }
}

Output result:

4. Multidimensional array

**Multidimensional arrays can be regarded as arrays with arrays as elements** There can be two-dimensional, three-dimensional, or even more dimensional arrays, but they are used in practical development

Very few. Up to two-dimensional arrays (after learning containers, we generally use containers, and two-dimensional arrays are rarely used).

[example] Declaration of two-dimensional array

import java.util.Arrays;
public class test06 {
    public static void main(String[] args) {
        //The declaration and initialization of multidimensional arrays in java should be carried out in the order from low dimension to high dimension
        int[][] a=new int[3][];
        a[0]=new int[2];
        a[1]=new int[4];
        a[2]=new int[3];
        //int a1[][]=new int[][4];// illegal
        System.out.println(Arrays.toString(a[0]));
        System.out.println(Arrays.toString(a[1]));
        System.out.println(Arrays.toString(a[2]));
    }
}

Output:

[example] static initialization of two-dimensional array

public class test06 {
	public static void main(String[ ] args) {
		int[ ][ ] a = { { 1, 2, 3 }, { 3, 4 }, { 3, 5, 6, 7 } };
		System.out.println(a[2][3]);  //  7
	}
}

[example] dynamic initialization of two-dimensional array

import java.util.Arrays;
public class test06 {
	public static void main(String[ ] args) {
		int[ ][ ] a = new int[3][ ];
		// a[0] = {1,2,5}; // Error initializing without declaring type
		a[0] = new int[ ] { 1, 2, 3, 4 };
		a[1] = new int[ ] { 2, 2 };
		a[2] = new int[ ] { 2, 2, 3, 4 };
		System.out.println(a[2][3]);
		System.out.println(Arrays.toString(a[0]));
        System.out.println(Arrays.toString(a[1]));
		System.out.println(Arrays.toString(a[2]));
	} 
}

Output result:

5. The array stores table data

Employee table

IDfull nameAgefunctionEntry date
1001K18lecturer2-14
1002Z19assistant4-21
1003Y20headmaster5-21

Observe the table and find that each row can be stored in a one-dimensional array:

Object [] A1 = {1001, "Gao Qi", 18, "lecturer", "2-14"};

Object [] A2 = {1002, "Gao Xiaoqi", 19, "teaching assistant", "10-10"};

Object [] A3 = {1003, "Gao Xiaoqin", 20, "head teacher", "5-5"};

Note: the basic data type "1001" here is not an Object in nature. The JAVA compiler will automatically "auto box" the basic data type into a wrapper class Object.

We only need to define another two-dimensional array and put the above three arrays into:

Object[ ][ ] emps = new Object[3][ ];

emps[0] = a1;

emps[1] = a2;

emps[2] = a3;

1. Use two-dimensional array to save table data

import java.util.Arrays;
public class test07 {
    public static void main(String[] args) {
        Object[] a1={1001,"K",18,"lecturer","2-14"};
        Object[] a2={1002,"Z",19,"assistant","4-21"};
        Object[] a3={1003,"Y",20,"director","5-21"};
        Object[][] emps=new Object[3][];
        emps[0]=a1;
        emps[1]=a2;
        emps[2]=a3;
        System.out.println(Arrays.toString(emps[0]));
        System.out.println(Arrays.toString(emps[1]));
        System.out.println(Arrays.toString(emps[2]));

        System.out.println("===============");
        for(int i=0;i<emps.length;i++){
            for(int j=0;j<emps[i].length;j++){
                System.out.print(emps[i][j]+"\t");
            }
            System.out.println();
        }
    }
}

Output result:

2. Use javabean and one-dimensional array to save table information

/**
 * Using javabean and one-dimensional array to save table information
 */
import java.util.Arrays;
public class test08{
    public static void main(String[] args) {
        Emp[] emps={
                new Emp(1001,"K",18,"lecturer","2-14"),
                new Emp(1002,"Z",19,"assistant","4-21"),
                new Emp(1003,"Y",20,"director","5-21")
        };
        for(Emp e:emps){
            System.out.println(e);
        }
    }
}

class Emp{
    private int id;
    private String name;
    private int age;
    private String job;
    private String hiredate;

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", job='" + job + '\'' +
                ", hiredate='" + hiredate + '\'' +
                '}';
    }

    public Emp(int id, String name, int age, String job, String hiredate) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.job = job;
        this.hiredate = hiredate;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getHiredate() {
        return hiredate;
    }

    public void setHiredate(String hiredate) {
        this.hiredate = hiredate;
    }
}

Execution result:

6.Comparable interface

To compare multiple objects, you need to have "comparison rules" and then sort them.

In fact, the bottom layer of sorting algorithm in java also depends on the Comparable interface.

There is only one method in the Comparable interface:

public int compareTo(Object obj)   // obj is the object to compare

Method, it is difficult to compare the current object with obj. If it is greater than 1, wait for 100 to return 0 and less than - 1 (1 here can also be a positive integer, - 1 can also be a negative integer). The code of compareTo method is also relatively fixed:

public int compareTo(Object o) {
	Man man = (Man) o;
	if (this.age < man.age) {
		return -1;
	}
	if (this.age > man.age) {
		return 1;
	}
	return 0;
}

[test Comparable interface] use the Arrays class to sort the array elements

/**
 * Test the Comparable interface
 */
import java.util.Arrays;
public class test09 {
    public static void main(String[] args) {
        Man2[] msMans={new Man2(3,"a"),new Man2(60,"b"),new Man2(2,"c")};
        System.out.println(Arrays.toString(msMans));
        Arrays.sort(msMans);
        System.out.println(Arrays.toString(msMans));
    }
}

class Man2 implements Comparable{
    int age;
    int id;
    String name;

    public Man2(int age, String name) {
        this.age = age;
        this.name = name;
    }

    @Override
    public String toString() {
        return this.name;
    }

    @Override
    public int compareTo(Object o) {
        Man2 man = (Man2) o;
        if (this.age < man.age) {
            return -1;
        }
        if (this.age > man.age) {
            return 1;
        }
        return 0;
    }
}

Output result:

7. Common algorithms

Animation demonstration website: https://visualgo.net/

1. Bubble sorting algorithm

a. Basic algorithm of bubble sorting

The bubble sorting algorithm repeatedly visits the sequence to be sorted and compares two elements at a time. If they are in the wrong order, they will be sorted

Exchange them so that the larger elements will slowly "float" to the top of the sequence through the exchange.

The operation of bubble sorting algorithm is as follows:

  1. Compare adjacent elements. If the first one is bigger than the second, exchange them.
  2. Do the same for each pair of adjacent elements, from the first pair at the beginning to the last pair at the end. At this point, the last element should be the largest number.
  3. Repeat the above steps for all elements except the last one.
  4. Continue to repeat the above steps for fewer and fewer elements at a time until no pair of numbers need to be compared.

[example] basic algorithm of bubble sorting

/**
 * Test bubble sorting basic algorithm
 */
import java.util.Arrays;
public class TestBuddleSort {
    public static void main(String[] args) {
        int[] values={3,1,6,8,9,0,7,4,5,2};
        bubbleSort(values);
        System.out.println(Arrays.toString(values));
    }

    public static void bubbleSort(int[] values){
        int temp;
        for(int i=0;i<values.length;i++){
            for(int j=0;j<values.length-1-i;j++){
                if (values[j] > values[j+1]){
                    temp=values[j];
                    values[j]=values[j+1];
                    values[j+1]=temp;
                }
            }
        }
    }
}

Execution result:

b. Optimization algorithm of bubble sorting

We can optimize the above bubble sorting algorithm based on the following characteristics of bubble sorting:

  1. The whole sequence is divided into two parts: unordered sequence in front and ordered sequence in the back.
  2. Judge whether the exchange of array elements occurs in each trip. If it does not occur, it indicates that the array is in order at this time, and there is no need to compare the number of subsequent trips. At this point, you can abort the comparison.

[example] optimization algorithm for bubble sorting

/**
 * Optimization algorithm of bubble sorting
 */
import java.util.Arrays;
public class TestBuddleSort2 {
    public static void main(String[] args) {
        int[] values={3,1,6,8,9,0,7,4,5,2};
        bubbleSort2(values);
        System.out.println(Arrays.toString(values));
    }

    public static void bubbleSort2(int[] values){
        int temp;

        for(int i=0;i<values.length;i++){
            //Define a boolean variable to mark whether the array has reached an ordered state
            boolean flag=true;
            /*Inner loop: each loop starts from the first two elements of the sequence and is compared to disorder
            Last of array*/
            for(int j=0;j<values.length-1-i;j++){
                //If the previous element is greater than the latter element, exchange the values of the two elements;
                if(values[j]>values[j+1]){
                    temp=values[j];
                    values[j]=values[j+1];
                    values[j+1]=temp;
                    //The exchange occurred in this trip, indicating that the array is in an unordered state in this trip and needs to be compared continuously;
                    flag=false;
                }
            }
            //Judge whether it is in order according to the value of the tag quantity. If it is in order, exit; If out of order, continue the cycle
            if(flag){
                break;
            }
            System.out.println((i+1)+"Sequence of times:"+Arrays.toString(values));
        }
    }
}

Execution result:

2. Dichotomy search

binary search is also called half search.

The basic idea of binary search is to set the elements in the array to be stored in the array in order from small to large. First, compare the given value key with the key of the element in the middle of the array. If it is equal, the search is successful; Otherwise, if the key is small, continue the dichotomy retrieval in the first half of the array; If the key is large, continue the dichotomy retrieval in the second half of the array.

In this way, the search interval will be reduced by half after one comparison, and continue until the search is successful or failed. Dichotomy retrieval is an efficient retrieval method.

import java.util.Arrays;
public class TestBinarySearch {
	public static void main(String[ ] args) {
		int[ ] arr = { 30,20,50,10,80,9,7,12,100,40,8};
		int searchWord = 20; // Number of to find
		Arrays.sort(arr); //Be sure to sort the array elements before binary search
		System.out.println(Arrays.toString(arr));
		System.out.println(searchWord+"Index of element:"+binarySearch(arr,searchWord));
}
	public static int binarySearch(int[ ] array, int value){
 		int low = 0;
 		int high = array.length - 1;
 		while(low <= high){
 			int middle = (low + high) / 2;
 			if(value == array[middle]){
 				return middle; //Returns the index position found in the query
 			}
			 if(value > array[middle]){
 				low = middle + 1;
 			}
 			if(value < array[middle]){
 				high = middle - 1;
			 }
 		}
 		return -1; //After the above cycle is completed, it indicates that it is not found, and - 1 is returned
 	} 
}

Execution result:

Topics: Java intellij-idea