
作者简介:一名大一在校生
个人主页:月亮嚼成星~
个人WeChat:yx1552029968
系列专栏:Java SE基础
每日一句:但愿每次回忆,对生活都不感到负疚
目录
数组的初识化包括两个方面:
在创建数组的时候直接赋值
-
- int []arr1=new int[]{1,2,3};
-
- int []arr2={1,2,3};
这两种方式都可以,在静态初始化的时候new int[]可以省略不写。
在创建数组的同时赋予数组的大小,到用的时候再给元素赋值
int []arr=new int[10];
- //赋值
- arr=new int[]{1,2,3};
for-each是for循环的另一种使用方式,在对数组的遍历中可以避免循环条件和更新语句的影响。
- for (int x: arr ) {
- System.out.println(x);
-
- }

- public class Test {
- public static void main(String[] args) {
- int []arr=new int[10];
- //赋值
- arr=new int[]{1,2,3};
- for (int x: arr ) {
- System.out.println(x);
-
- }
- }
-
- }

在Java中数组是引用类型,引用数据类型创建的变量,一般称为对象的引用,其空间中存储的是对象所在空间的地址。为了方便理解,我们看一下它在栈帧中的情况:
- public class Test {
- public static void main(String[] args) {
-
- int a=10;
- int b=20;
- int[] array=new int[]{1,2,3};
- }
-
- }

Java中的引用类似于C语言中的指针,但是比指针容易理解和简单一点,用法上也体现了面向对象。
null在C语言中通常是指针指向空,但在Java里面没有指针的概念,null通常是数组的空引用,就是不指向对象的引用。在一些程序中要记得数组空引用的判断。
这个是Java数组带的包中其中的一个用法,它可以直接帮助我们实现数组到字符串的转换,是一个非常好用的工具。
- import java.util.Arrays;
-
- public class Test {
- public static void main(String[] args) {
-
-
- int[] array=new int[]{1,2,3};
- String str= Arrays.toString(array);
- System.out.println(str);
- }
-
- }

在利用这个包的时候记得加提供的包:
import java.util.Arrays;
二维数组本质上也就是一维数组, 只不过每个元素又是一个一维数组.


int[][] array1 = new int[3][];//在Java中可以省略列数但不能省略行数
- public class Test {
- public static void main(String[] args) {
-
- int[][]arr=new int[][]{{1,2,3},{4,5,6},{7,8,9}};
- for (int i = 0; i < arr.length; i++) {
- for (int j = 0; j
-
- System.out.printf("%d ",arr[i][j]);
-
- }
- System.out.println();
- }
-
- }
-
- }

🐬 二维数组的几种打印方式
1):Arrays类的deepToStirng方法
- public static void main(String[] args) {
- int[][] array ={{1,2,3,4,5},{6,7,8},{5,6,5,2}};
- System.out.println(Arrays.deepToString(array));
- }
2):普通for循环打印二维数组
- public static void main(String[] args) {
- int[][] array ={{1,2,3,4,5},{6,7,8},{5,6,5,2}};
- for (int i = 0; i < array.length; i++) {
- for (int j = 0; j < array[i].length; j++) {
- System.out.print(array[i][j]+" ");
- }
- System.out.println();
- }
- }
3):foreach循环打印二维数组
- public static void main(String[] args) {
- int[][] array ={{1,2,3,4,5},{6,7,8},{5,6,5,2}};
- for (int[] tmp:array) {
- for (int x:tmp) {
- System.out.print(x+" ");
- }
- System.out.println();
- }
- }