栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java数组的定义与使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java数组的定义与使用

目录

1.数组的定义

2.一维数组的存储方式

数组的长度

数组的第一个元素

数组的最后一个元素

数组的越界问题

3.一维数组遍历

使用for循环遍历

使用for...each(增强性for循环)遍历

4.二维数组定义

5.数组扩容

(1)底层的数据扩容

(2)使用Java方法进行数组扩容


1.数组的定义

数组是用来存储固定大小的同类型的元素。

public class Arraymypractise {

	public static void main(String[] args) {
		
		int[] a = {4,5,6,7,8};
		System.out.println(a[2]);
		
		
		int[] b = new int[8];
		Random ran = new Random();
		for (int i = 0; i < b.length; i++) {
			b[i] = ran.nextInt(9)+1; //随机产生1-10内的整数
		}
		for (int j = 0; j < b.length; j++) {
			System.out.print(b[j]+"  ");
		}
		System.out.println();//换行
		
		
		int[] c = new int[] {1,2,3,4,5,6};//使用较少
		System.out.println(c[4]);
	}
}

2.一维数组的存储方式

         int[] a= {4,5,6,7,8}定义后了数组a后,在内存中会划分出一片连续的存储空间,如上图所示,存放一个有5个整形元素的数组。

  • 数组的长度

  • 数组的第一个元素

  • 数组的最后一个元素

  • 数组的越界问题

public class Arraymypractise {

	public static void main(String[] args) {
		int[] array = {7,4,9,'0','u4e09'};

		System.out.println("数组的长度:"+array.length);
		System.out.println("第一个元素:"+array[0]);
		System.out.println("最后一个元素:"+array[array.length-1]);
		//越界问题    元素要在array[0]~array[length-1]
		System.out.println(array[7]);	
	}
}

3.一维数组遍历
  • 使用for循环遍历

  • 使用for...each(增强性for循环)遍历

public class Arraymypractise {

	public static void main(String[] args) {
		
		int[] array = {7,4,9,10,82,78,2};
		bianli(array);
		System.out.println();
		bianli1(array);
	}
	
	
	public static void bianli(int[] b) {
		for (int i = 0; i < b.length; i++) {
			System.out.print(b[i]+"  ");
		}
	}
	
	
	public static void bianli1(int[] b) {
		for (int t : b) {
			System.out.print(t+"  ");
		}
	}	
}

4.二维数组定义
public class erweiMyarray {
	public static void main(String[] args) {
		
		int[] [] a = new int[3] [4];
		
		int[] [] b = new int[5] [];
	}
}

5.数组扩容

(1)底层的数据扩容
public static void add() {
	if (index >= students.length) { index是数组的下标
		
		//int stuSize = students.length *2;    1.原数组长度*2=新数组长度(完成扩容)

		int newLength = students.length + (students.length>>1);//右移1位相当于÷2
		String[][] ss = new String[newLength][4];
		
		for (int i = 0; i < students.length; i++) {
			ss[i] = students[i];
		}
			
		students = ss;// students连接新数组
	}
    students[index++] = stu;
}

(2)使用Java方法进行数组扩容
public static void add() {
	if (index >= students.length) {  //index是数组的下标
		
		int newLength = students.length + (students.length>>1);//右移1位相当于÷2
		String[][] ss = new String[newLength][4];
			
		//String[][] ss = Arrays.copyOf(students, newLength);
			
		
		System.arraycopy(students, 0, ss, 0, students.length);
		students = ss;// students连接新数组
	}
    students[index++] = stu;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/602666.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号