Java学习数组

2020-11-26  本文已影响0人  噜啦噜啦嘞_d31b
数组.png

一、数组

1.1 数组变量的声明
  1. 声明数组的方式:
      第一种:  数据类型[ ] 数组名字 = new 数据类型[长度] 
      第二种:数据类型[ ] 数组名字 = new 数据类型[ ]{元素1,。。。}
      第三种: 数据类型[ ] 数组名字 = { 元素,···}
1.2 数组的初始化
int[] Array = {0, 1};
int[] Array = new int[]{0, 1};
Student sArray[] = new Student[] { new Student(“George”, “Male”, 20), new Student()};
Student[] stArray = { new Student(), new Student()} ;

 
int[] x = new int[5]{5,4,3,2,1};  //编译出错,创建数组对象的同时并初始化的时候就不能指定数组长度了;
int[] x;   x = {5,4,3,2,1};  //{5,4,3,2,1}必须在声明数组变量的语句中使用,不能单独使用
1.3 数组的访问

索引: 从0开始,索引(index)可以访问到数组种的元素
格式: 数组名[索引]

public static void main(String[] args) { 
      int[] arr = new int[]{1,2,3,4,5}; 
      //打印数组的属性,输出结果是5 
      System.out.println(arr.length); 
}
1.4 内存

内存是计算机中的重要原件,临时存储区域,作用是运行程序。我们编写的程序是存放在硬盘中的,在硬盘中的程 序是不会运行的,必须放进内存中才能运行,运行完毕后会清空内存。 Java虚拟机要运行程序,必须要对内存进行空间的分配和管理

1.5 java虚拟机的内存划分
1.6 数组在内存中的存储
单独一个.png
两个数组.png
两个数组指向同一片内存.png
1.7 数组的遍历
//for循环
 public static void main(String[] args) { 
     int[] arr = { 1, 2, 3, 4, 5 }; 
     for (int i = 0; i < arr.length; i++) {
     System.out.println(arr[i])
        } 
      } 

//foreach循环
public static void main(String[] args){
      int [] arr = {1,2,3,4,5};
      for(int i:arr){
            System.out.print(i+" ");
      }
}


上一篇 下一篇

猜你喜欢

热点阅读