【Java】の配列
配列のデータの従来のfor文と拡張for文の比較
従来のfor文
public class Main { public static void main(String[] args){ int[] score = {1, 2, 3, 4, 5}; for (int i = 0; i < score.length; i++) { System.out.println(score[i]); } } } 1 2 3 4 5
拡張for文
public class Main { public static void main(String[] args){ int[] score = {1, 2, 3, 4, 5}; for (int value : score) { System.out.println(value); } } } 1 2 3 4 5
引数に配列を用いる
メソッドんp引数にはint型やString型などの変数だけでなく
配列も使う事が出来る。
public class Main { public static void main(String[] args){ int[] array = {1,2,3}; printArray(array); } public static void printArray(int[] array) { for (int element : array) { System.out.println(element); } } } 1 2 3
戻り値に配列を用いる
public class Main { public static int[] makeArray(int size) { int[] newArray = new int[size]; for (int i = 0; i < newArray.length; i++) { newArray[i] = i; } return newArray; } public static void main(String[] args) { int[] array = makeArray(3); for (int i : array) { System.out.println(i); } } } 0 1 2