Learn Java - Chapter 1 变量(Variables)-数组(Arrays)

Java数组在被创建的时候确定数组长度。索引下标从0开始。

Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the first element in the array

1.数组定义及初始化

int[] anArray;//定义
anArray = new int[2];//初始化
anArray[0] = 100;//赋值
anArray[1] = 200;//赋值
  
System.out.println("Element at index 0: " + anArray[0]);//使用
System.out.println("Element at index 1: " + anArray[1]);//使用

程序输出:

Element at index 0: 100
Element at index 1: 200

2.定义初始化同时赋值

int[] anArray = { 
    100, 200, 300,
    400, 500, 600, 
    700, 800, 900, 1000
};

3.多维数组

String[][] names = {
    {"Mr. ", "Mrs. ", "Ms. "},
    {"Smith", "Jones"}
};
System.out.println(names[0][0] + names[1][0]);
System.out.println(names[0][2] + names[1][1]);

程序输出:

Mr. Smith
Ms. Jones

从以上例子中可以看出,Java多维数组每一行数组的长度不要求相等。

4.复制数组

    

class ArrayCopyDemo {
    public static void main(String[] args) {
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
			    'i', 'n', 'a', 't', 'e', 'd' };
        char[] copyTo = new char[7];

        System.arraycopy(copyFrom, 2, copyTo, 0, 7);
        System.out.println(new String(copyTo));
    }
}

程序输出:

caffein

5.Arrays工具类

Java SE提供了java.util.Arrays工具类操作数组,常用的方法有:

搜索:binarySearch 

比较:equals 

填充:fill 

排序:sort (sort 自定义类时,可以根据业务重写业务对象的sort方法来实现业务排序),Java 8还新添了方法parallelSort来进行数组的并行排序。

转载于:https://my.oschina.net/hassan/blog/423466

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值