JAVA Getting Started Tutorial--Array

1. 配列の概念
配列とは、同じ型のデータを順序付けて格納したコレクションです。各データは要素と呼ばれ、
インデックス (添字、0 から始まる) を通じてアクセスできます。

2. 配列の特徴
長さは固定です。配列は一度作成すると、サイズを変更できません。
配列の型には、プリミティブ型や参照型など、あらゆるデータ型を指定できます。
要素の型はすべて同じでなければならず、異なる型を混在させることはできません。
配列変数は参照型であり、配列もオブジェクトです。配列の要素はオブジェクトのプロパティに相当します。
3 配列の宣言方法
3.1 方法 1
type[ ] arr_name;
3.2 方法 2
type arr_name[ ];
注意:宣言時はまだインスタンス化されていません

配列を宣言しても、実際にはまだ作成されていません

4 配列の作成
4.1 プリミティブ型の一次元配列の作成
public class Test {
public static void main(String args[]) {
int[] a; // 配列を宣言
a = new int[10]; // 配列にメモリを割り当て
for (int i = 0; i < 10; i++) {
a[i] = i ;// 配列要素に値を代入。配列はオブジェクトであり、配列の要素はオブジェクトのプロパティ
System.out.println(a[i]);
}
}
}
実行結果は次のとおりです。

insert image description here

4.2 参照型配列の作成
class Student {
private int age;
private int id;

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

public class Test {
public static void main(String[] args) {
Student[] students; // 参照型配列を宣言
students = new Student[10]; // 参照型配列にメモリを割り当て
Student s1 = new Student(1, 11);
Student s2 = new Student(2, 22);
students[0] = s1;// 参照型配列要素に値を代入
students[1] = s2;// 参照型配列要素に値を代入
}
}
5 初期化
5.1 静的初期化
int [ ] a = { 1, 2, 3 };// プリミティブ型配列の静的初期化
Student[ ] student= { new Student(1, 1), new Student(2, 2) };// 参照型配列の静的初期化
5.2 動的初期化
int[ ] a = new int[2];// 配列を動的に初期化し、まずメモリを割り当て
a[0]=1;// 配列要素に値を代入
a[1]=1;// 配列要素に値を代入
5.3 デフォルト初期化
int a[ ] = new int[2];
boolean[ ] b = new boolean[2];
String[ ] s = new String[2];

Related Articles

Explore More Special Offers

  1. Short Message Service(SMS) & Mail Service

    50,000 email package starts as low as USD 1.99, 120 short messages start at only USD 1.00

phone お問い合わせ
Hi, I'm Alibaba Cloud AI Assistant!
I can help with questions and solutions.