首页 > 编程语言 > 详细

数组 java

时间:2020-10-14 00:21:24      阅读:48      评论:0      收藏:0      [点我收藏+]
数组
动态初始化:int[] a = new int[5];
静态初始化:int[] a = new int []{1,2,3,4,5};
      int[] a ={1,2,3,4,5};

技术分享图片

 

获取数组长度  数组名.length

数组下标一般由0开始,到数组的长度减1(a.length-1)

数组一旦创建,长度就不变

==============================================================================

 

//简单的遍历数组,存入1到10
import java.util.Arrays;
public class T1 {
public static void main(String[] args) {
function();
}

private static void function(){
int [] arr = new int [10];
for (int i = 0; i < arr.length; i++) {
arr[i] = i+1;
}
System.out.println(Arrays.toString(arr));
}
}

 


======================================================================================


import java.util.Arrays;
public class C2 {
public static void main(String[] args) {
method();//toString 转字符串
method2();//sort 排序
method3();// copyOf() 复制数组
/*
* sort 没有返回值 copyOf有,因为前面是在数组内排序,而后者
* 是创建新的数组,而且长度发生了变化,所以需要返回值
* 注意:创建了数组后,长度不可变化
* */
}

public static void method() {
char[] a = {‘r‘, ‘a‘, ‘s‘, ‘h‘};
int[] b = {1, 24, 2, 5};

System.out.println(a);// 打印 rash
//System.out.println(b);//[I@14ae5a5 打印地址值 [ 数组 I int类型 @在哪里

System.out.println(Arrays.toString(b));
}

public static void method2() {
int[] a = {6, 81, 16, 1, 24, -1, 52, 5, 10};
Arrays.sort(a);//排序(快排)
System.out.println(Arrays.toString(a));
}

public static void method3() {
int[] a = {1,2,5,3,6};
int[] newA = Arrays.copyOf(a,10);
//第一个参数是原来数组名 第二个参数是新数组长度
System.out.println(Arrays.toString(newA));
//复制完后,新数组比原来的大。加了几个位置扩容

int[] newB = Arrays.copyOf(a,3);
System.out.println(Arrays.toString(newB));
//复制完后,新数组比原来的小。缩容
}
}

数组 java

原文:https://www.cnblogs.com/liang-shi/p/13812444.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!