文章目录
- 数组的创建
- 数组的遍历
数组的创建
方法一:
package cn.xu.arrays;
import java.util.Arrays;
public class Example2 {
public static void main(String[] args) {
int[] ns;
ns = new int[5];
System.out.println(ns[0]);
}
}
方法二:
初始化并且赋值,把[]的数字去掉,让编译器计算有多少个值,new可以省略掉编译器会给我们加上,这是一种语法糖。
package cn.xu.arrays;
import java.util.Arrays;
public class Example2 {
public static void main(String[] args) {
int[] a = {1,2,3,4,5,6};
// int[] a = new int[] {1,2,3,4,5,6};
System.out.println(a[0]);
}
}
数组的遍历
第一种:用for循环遍历
package cn.xu.arrays;
import java.util.Arrays;
public class Example2 {
public static void main(String[] args) {
int[] a = new int[] {1,2,3,4,5,6};
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
第二种:类似迭代器
package cn.xu.arrays;
import java.util.Arrays;
public class Example2 {
public static void main(String[] args) {
int[] a = new int[] {1,2,3,4,5,6};
for (int n : a){
System.out.println(n);
}
}
}