Java beginners briefly summarized the behavior of Array and ArrayList

Introduction

I didn't understand the behavior of Java Array and ArrayList well, so I tried to summarize the parts that are likely to be used frequently.

Sample code

Main1 describes how to create Array and Main2 describes how to create ArrayList and how to get values. Main3 and Main4 describe each multidimensional array.

Main1

Main1.java


import java.util.Arrays;

/**
 * Created 2017/05/24.
 *List of normal Array behavior in Main1
 */
public class Main1 {
  public static void main(String[] args) {
    
    //How to create an array
    //Declaration method 1
    
    //Declare the type and name of the array
    //int[] num;  
    
    //Secure the area to use
    //num = new int[3];             

    //Declaration method 2
    //How to do the above method at the same time
    int[] num = new int[3];               

    //Storage in an array
    num[0] = 1;
    num[1] = 2;
    num[2] = 3;

    //When you do everything from creation to storage
    // int[] num = {1, 2, 3};

    //Extraction of array
    System.out.println(num[0]);
    //Execution result: 1

    //How to take out all at once

    //When looping with a normal for statement
    for (int i = 0; i < num.length; i++) {
      System.out.print(num[i] + " ");
      //Execution result: 1 2 3
    }

    System.out.println(" ");                //I put it in for the appearance after execution

    //When using an extended for statement
    for (int value : num) {               
      //value is an arbitrary variable name,Unlike ordinary for, use the variable name as it is
      System.out.print(value + " ");      
      //Execution result: 1 2 3
    }
    System.out.println(" ");                //Same as above

    //How to display the contents of an array at once (p method in Ruby)
    // Arrays.It feels good to use toString
    //As a precaution when using, import java when using.util.Arrays;Need to declare
    //The other is Arrays when the target array is a multidimensional array.Must be written as deepToString
    
    System.out.println(Arrays.toString(num));
    //Execution result:[1, 2, 3]

    //If you write it like this, it becomes a mysterious character string
    System.out.println(num);
    //Execution result:[I@1540e19d


    //Supplementary rules and so on
    //Array cannot store more than the number of elements declared at the beginning
    //num[3] = 4;  //It doesn't make sense to write to store 4 in the 4th of the array, it doesn't actually fit
    //System.out.println(num[3]);
    //As a behavior, there is no compilation error, but there is an execution error.
    //Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:Get angry like 3
    //Also, where the storage declaration in the array is not made, for example, num[5]And num[6]I get the same error when trying to display the value of
  }
}

Execution result

Main1.Java


1
1 2 3  
1 2 3  
[1, 2, 3]
[I@1540e19d

Main2

Main2.java


import java.util.ArrayList;

/**
 * Created 2017/05/24.
 *Main2 describes the normal behavior of ArraysList
 */
public class Main2 {
  public static void main(String[] args) {
    //How to create an ArrayList
    //Basic declaration
    //ArrayList<Integer> num = new ArrayList<Integer>();

    //Definition example of Java SE 7 or later
    ArrayList<Integer> num = new ArrayList<>();

    //Supplement
    //new ArrayList<>();of()は、数値を入れることで、配列of初期サイズを決めることが出来る
    
    //Storage method
    //use add method
    //Add as a way of writing(Data you want to store), or add(Index (storage position),Data you want to store)Described in
    //It is basically stored in order
    //If the value already exists when the index is specified,Note that the value is stored so that it shifts horizontally instead of overwriting it.
    num.add(1);
    num.add(1, 2);
    num.add(3);
    //num.add(2,4);
    //If you add like this,[1,2,4]Not[1,2,4,3]Please note that the array will be
    //If you want to update the value num.set(2,4);like,.set()With[1.2,4]Can be obtained

    //Extracting the value
    
    //get()Use method
    System.out.println(num.get(0));
    //Execution result: 1
    

    //Take out the hand
    //for statement
    //For ArrayList, to get the number of elements.size()use
    for (int i = 0; i < num.size(); i++) { 
      System.out.print(num.get(i) + " ");
      //Execution result:1 2 3
    }
    
    System.out.println(" ");

    //Extended for statement
    for (int value : num) {
      System.out.print(value + " ");
      //Execution result:1 2 3
    }
    
    System.out.println(" ");

    //When displaying all at once like the p method, just put it in println as it is
    System.out.println(num);
    //Execution result:[1, 2, 3]
  }
}

Execution result

Main2.java


1
1 2 3  
1 2 3  
[1, 2, 3]

Main3

Main3.java


import java.util.Arrays;

/**
 * Created 2017/05/24.
 *In Main3, a list of behavior when creating a multidimensional array in a normal Array
 */
public class Main3 {
  public static void main(String[] args){
    //Declaration and creation
    int [][] num = new int[2][3];
    
    //Value storage
    num[0][0] = 1;
    num[0][1] = 2;
    num[0][2] = 3;
    num[1][0] = 10;
    num[1][1] = 11;
    num[1][2] = 12;
    
    //How to retrieve the value
    System.out.println(num[0][0]);
    //Execution result:1
    System.out.println(num[1][2]);
    //Execution result:12
    
    //When taking out all at once
    //Double loop using for
    //i is the total number of elements in num, num.Loop by length
    for(int i = 0; i < num.length; i++){
      //j is the number of elements in each array, num[i].Loop to length
      for(int j = 0; j < num[i].length;j++){
        System.out.print(num[i][j] + " ");
        //Execution result: 1 2 3 10 11 12
      }
    }

    System.out.println(" ");
    
    //For extended for
    //This is also written in a double loop
    //Specify an array as the data to retrieve
    for(int[] index : num) {
      //Next, take out the contents from the array
      for (int element : index) {
        System.out.print(element + " ");
        //Execution result: 1 2 3 10 11 12
      }
    }

    System.out.println(" ");
    
    //Batch display
    //Arrays for multidimensional arrays.deepToString();use
    System.out.println(Arrays.deepToString(num));
    //Execution result:[[1, 2, 3], [10, 11, 12]]
  }
}

Execution result

Main3.java


1
12
1 2 3 10 11 12  
1 2 3 10 11 12  
[[1, 2, 3], [10, 11, 12]]

Main4

Main4.java


import java.util.ArrayList;

/**
 * Created 2017/05/24.
 *  *Main4 describes the multidimensional behavior of ArraysList
 *I can understand it, but it's hard to handle
 */
public class Main4 {
  public static void main(String[] args){
    //How to make a two-dimensional ArrayList
    //First, create two ordinary ArrayLists)
    ArrayList<Integer> num1 = new ArrayList(); 
    num1.add(1);
    num1.add(2);
    num1.add(3);
    
    System.out.println(num1);
    //Execution result:[1, 2, 3]
    
    ArrayList<Integer> num2 = new ArrayList<Integer>();
    num2.add(10);
    num2.add(11);
    num2.add(12);

    System.out.println(num2);
    //Execution result:[10, 11, 12]
    
    //Next, create an ArrayList to store, pay attention to the data type to declare
    //When declaring the data type, the data to be stored is "ArrayList"<Integer>Store! Can be entered by declaring
    ArrayList<ArrayList<Integer>> num_list =new ArrayList<>();
    num_list.add(num1);
    num_list.add(num2);
    
    //How to take out
    //.get().get()Take out with
    System.out.println(num_list.get(0).get(0));
    //Execution result:1
    System.out.println(num_list.get(0).get(2));
    //Execution result:3
    System.out.println(num_list.get(1).get(0));
    //Execution result:10
    
    //Take out all
    //for
    //i is the total number of elements in num, num.size()Loop with
    for(int i = 0; i < num_list.size(); i++){
      //j is the number of elements in each array, num[i].size(()Loop to
      for(int j = 0; j < num_list.get(i).size();j++){ 
        System.out.print(num_list.get(i).get(j) + " ");
        //Execution result:1 2 3 10 11 12
      }
    }
    System.out.println(" ");
    
    //Extension for
    //ArrayList in variable declaration<Integer>If you declare it with + variable name, you can pull the value!
    for(ArrayList<Integer> index : num_list) {
      //The rest is described in a normal extended for statement
      for (int element : index) {
        System.out.print(element + " ");
        //Execution result:1 2 3 10 11 12
      }
    }

    System.out.println(" ");
    
    //Batch display
    System.out.println(num_list);
    //Execution result:[[1, 2, 3], [10, 11, 12]]
    
    //How to add a value
    //.add()You can use, but is there no choice but to add each array or create a new array and add it?
    //num_list.add()I want to add it directly in the form of, but I do not know after all
    
    num1.add(4);
    num2.add(13);
    
    //Add new array
    ArrayList<Integer> num3 = new ArrayList<Integer>();
    num3.add(20);
    num3.add(21);
    num3.add(22);
    
    num_list.add(num3);
    
    System.out.println(num_list);
    //Execution result[[1, 2, 3, 4], [10, 11, 12, 13], [20, 21, 22]]
  }
}

Execution result

Main4.java


[1, 2, 3]
[10, 11, 12]
1
3
10
1 2 3 10 11 12  
1 2 3 10 11 12  
[[1, 2, 3], [10, 11, 12]]
[[1, 2, 3, 4], [10, 11, 12, 13], [20, 21, 22]]

Impressions

Originally I was doing Ruby, so a variable length array like ArrayList was intuitively easier to use. When it comes to multidimensional arrays, ArrayList is a mess and it's hard to understand. I still don't know how to use these two, so I would like to study hard.

Recommended Posts

Java beginners briefly summarized the behavior of Array and ArrayList
I summarized the types and basics of Java exceptions
[Java] Difference between array and ArrayList
Compare the elements of an array (Java)
[day: 5] I summarized the basics of Java
[Java] [Spring] Test the behavior of the logger
[Java] The confusing part of String and StringBuilder
I compared the characteristics of Java and .NET
ArrayList and the role of the interface seen from List
Summary of ToString behavior with Java and Groovy annotations
Please note the division (division) of java kotlin Int and Int
[For beginners] DI ~ The basics of DI and DI in Spring ~
[For beginners] Quickly understand the basics of Java 8 Lambda
Convert the array of errors.full_messages to characters and output
Organizing the current state of Java and considering the future
Java language from the perspective of Kotlin and C #
Check the behavior of Java Intrinsic Locks with bpftrace
Behavior is different between new and clear () of ArrayList
List of frequently used Java instructions (for beginners and beginners)
[For beginners] Explanation of classes, instances, and statics in Java
[Note] Java Output of the sum of odd and even elements
behavior of didSet and willSet
[Java] Beginner's understanding of Servlet-②
I tried to summarize the basics of kotlin and java
A program (Java) that outputs the sum of odd and even numbers in an array
[Java] Beginner's understanding of Servlet-①
Regarding the difference between Java array and ArrayList, I compared and corresponded methods with similar functions.
Advantages and disadvantages of Java
[Java] Convert ArrayList to array
[Java] I thought about the merits and uses of "interface"
[Java] Various summaries attached to the heads of classes and members
Utilization of Java array elements, for, length, value, and extended for statements
[Java] Get the dates of the past Monday and Sunday in order
[Swift5] How to get an array and the complement of arrays
The story of not knowing the behavior of String by passing Java by reference
About the relationship between the Java String equality operator (==) and initialization. Beginners
Read the first 4 bytes of the Java class file and output CAFEBABE
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
I tried to summarize the methods of Java String and StringBuilder
I passed the Oracle Java Bronze, so I summarized the outline of the exam.
The behavior of JS running on `Java SE 8 Nashorn` suddenly changed
About the behavior of ruby Hash # ==
[Java] Delete the elements of List
[For beginners] Summary of java constructor
About fastqc of Biocontainers and Java
Java for beginners, expressions and operators 1
[Java version] The story of serialization
I read the source of ArrayList I read
Java for beginners, expressions and operators 2
[Java] Declare and initialize an array
This and that of the JDK
Java basic learning content 2 (array / ArrayList)
Beginners examined webpack and summarized it
[Java] Judgment of identity and equivalence
About removeAll and retainAll of ArrayList
Classes and instances Java for beginners
The origin of Java lambda expressions
[Java] Convert array to ArrayList * Caution
[Rails] Difference in behavior between delegate and has_many-through in the case of one-to-one-to-many
Dynamically increase the number of elements in a Java 2D array (multidimensional array)
A collection of phrases that impresses the "different feeling" of Java and JavaScript