リュックに何いれる?

一人暮らし・itエンジニア・読書

【Java SE 11 Silver対策】黒本5章(配列の操作)チェックリスト

今回は調べたわけではなく、「5章 配列の操作」をまとめた内容になります。


・配列型変数の宣言
以下、全部OK
int a;
int b
;
int c;
int d ;
int e;
int f;

 

・宣言時に要素の指定をしてはいけない。
int[3] a; はNG
配列型変数にはインスタンスの参照が入るだけ。要素がいくつかどうかは無関係

 

・配列インスタンスの作成時は、必ず要素数を指定する
int a = new int; はNG

int a = new int[2]; はOK

 

・要素数は必ずint型の整数値
int a = new int[1L]; はNG
int
a = new int[1.2]; はNG

 

・変数とインスタンスの次元数は必ず一致
int a = new int[2][3]; はNG

int a = new int[2][3]; はOK

 

・1次元目の要素の省略はできない。2次元目はできる。

以下、NG
int a = new int[4];

以下、OK
int a = new int[3];
a[0] = new int[2];
a[1] = new int[3];
a[2] = new int[4];

 

・配列のインスタンスを作成しても要素自体は作成されない。
int a = new int[2]
上記の記述をしても、a[0]にはまだ何も入っていない。
デフォルト値は以下になる。
整数値:0
浮動小数点数:0.0
真偽値:false
文字列型:\u0000
オブジェクト型:null

Item items = new Item[2];
item[0].price; ← item[0]がnullなので、実行時にNullPointerException発生

 

・配列のインスタンスの生成と要素の初期化を同時に行うには
int a = {1,2,3};
int
b = {{1,2},{3,4,5},{6}};

 

・配列のインスタンスの生成と要素の初期化の方法は二つ

以下はOK
①int a = {1,2,3};
②int a = new int{1,2,3};

以下はNG

int a = new int[3]{1,2,3};

 

・要素0のインスタンスの作成(コンパイルエラーは出ない)
int array1 = {};
int array2 = new int[0];
int
array3 = new int{};
int
array4 = {};
int
array5 = new int[0][0];
int
array6 = new int{};

 

・初期化子を使う際の注意。初期化子を記述する行に次元数が記入されていればOK
以下はOK
int b = {1,2,3};
int c;
c = new int
{1,2,3};
int d;
d = new int{};
以下はNG
int e;
e = {1,2,3};

 

・cloneメソッドについて
public class Main {
    public static void main(String args) throws Exception {
        int arrayA = {1,2,3};
        //cloneメソッドで同じ値を持った配列インスタンスを複製
        int
arrayB = arrayA.clone();
        //複製したので、もちろんインスタンス(参照先)は異なる
        System.out.println(arrayA == arrayB);
        for (int i : arrayB){
            System.out.println(i);
        }
        
        int arrayC = {{1},{2,3},{4,5,6}};
        int arrayD = arrayC.clone();
        //2次元配列の場合、1次元目のインスタンスは別のインスタンス
        System.out.println(arrayC == arrayD);
        //ただし、2次元目のインスタンスは同じインスタンス(同じ参照を持っている)
        System.out.println(arrayC[0] == arrayD[0]);
    }
}

◆出力
false
1
2
3
false
true

 


以上、おわり!

 

Silverの勉強も大詰め!