0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Java】配列ノート

Last updated at Posted at 2019-04-17

配列#

  • 配列の種類
    • 配列
    • 多次元配列
  • 配列のfor構文
    • 拡張for構文
  • int配列要素の平均計算のサンプルプログラム

配列の種類##

配列###

略記法が楽だから使っていきたいが、ガベージのことを考えると、newを使う正式な書き方もしっかり覚えておきたい。ガベージコレクションがあるとはいえ、省略されているところにnewがあると、しっかり自覚を持って略記法を書くこと。

// 正式な書き方
int[] scores; //配列変数の宣言
scores = new int[3]; //配列要素の宣言
scores[0]=10; //配列要素代入
scores[1]=20;
scores[2]=30;

// 略記法
int[] scores = new int[]{10,20,30};
int[] scores = {10,20,30};

// すべて等価

多次元配列###

// 正式な書き方
String[][] scores = new String[2][3];
scores[0][0]="A1";
scores[0][1]="A2";
scores[0][2]="A3";
scores[1][0]="B1";
scores[1][1]="B2";
scores[1][2]="B3";

// 多次元配列の略記法
String[][] scores = {{"A1","A2","A3"},{"B1","B2","B3"}};

// すべて等価

配列のfor構文と拡張for構文

配列名.length:これで配列要素の個数を取得して利用

// 配列の作成
int[] scores = {10,20,30};

// 一般的なfor構文
for (int i=0; i<scores.length; i++){
	System.out.println(scores[i]);
}

// 拡張for構文
for (int value:scores){
	System.out.println(values);
}

多次元配列の場合###


// 配列の作成
int scores[][]={{10,11,12},{21,22,23}};

// 一般的なfor構文
for(int i=0; i<scores.length; i++){
	for(int ii=0; ii<scores[i].length; ii++){
		System.out.println(scores[i][ii]);
	}
}

参考書籍#

[スッキリわかるJava入門第2版]
(https://www.amazon.co.jp/dp/B00MIM1KFC/ref=dp-kindle-redirect?_encoding=UTF8&btkr=1)
Pp.138-166

0
1
1

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?