0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Java 配列 

Posted at

配列にnullを入れるとNullPointerExceptionが投げられる
2つ目の要素がどこも参照していないため

	String [][]array = {{"A","B"},null,{"C","B","D"}};
		int total = 0;
		for(String[]temp:array) {
			total += temp.length;
		}
		
		System.out.println(total);

これはok
要素の値として入れているため

String [][]array = {{"A","B"},{"C","B","D"}};
array[0][0] = null;
  	int total = 0;
  	for(String[]temp:array) {
  		total += temp.length;
  	}
  	
  	System.out.println(total);

これもok
[1][0]の値として入っているため

 String [][]array = {{"A","B"},{null},{"C","B","D"}};
		int total = 0;
		for(String[]temp:array) {
			total += temp.length;
		}
		
		System.out.println(total);

ArrayListにはnullを入れてもNullPointerExceptionは投げられない

ArrayList<String>list = new ArrayList<>();
list.add(null);
System.out.println(list.get(0));

配列型変数宣言

コンパイルエラーにならない宣言

int [] a;
int b [];
int [][] c;
int d [][];
int [] e[];
int [][] f[];

コンパイルエラーになる宣言

int[2]a;

配列型変数に要素数を指定することはできない

配列インスタンス

コンパイルエラーになる宣言

int [] array1 = new int []; //要素数を指定していない
int [] array2 = new int[2.3]; //不動小数点は使えない
int [] array3 = new int[2]{}; //{}を使う場合要素数の指定はできない

int [][] array4 = new int []{} //次元数の不一致


要素数の指定にはint型を使う。long型は使えない

多次元配列

	
		String [] arrays = new String[] {"1次元配列"};
		String [][]arrays1 = new String[][] {{"2次元配列は大かっこ2こ"}};
		String [][][]arrays2 = new String [][][] {{{"3次元配列は大かっこ3こ"}}};
		
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?