声明方式
type[] arr_name; //(推荐使用这种方式)
type arr_name[];
public class Test {
public static void main(String args[]) {
int[] s = null; // 声明数组;
s = new int[10]; // 给数组分配空间;
for (int i = 0; i < 10; i++) {
s[i] = 2 * i + 1;//给数组元素赋值;
System.out.println(s[i]); //数组输出
}
// System.out.println(Arrays.toString(c)); 数组输出
}
}
for-each循环
专门用于读取数组或集合中所有的元素,即对数组进行遍历。
public class Test {
public static void main(String[] args) {
String[] ss = { "aa", "bbb", "ccc", "ddd" };
for (String temp : ss) { //循环遍历数组ss 把每个元素放入temp中输出
System.out.println(temp);
}
}
}
数组拷贝
static void arraycopy(object src,int srcpos,object dest, int destpos,int length)
该方法可以将src数组里的元素值赋给dest数组的元素,其中srcpos指定从src数组的第几个元素开始赋值,destpos指定拷贝到目标的第几个位置,length参数指定将src数组的多少个元素赋给dest数组的元素
public class TextArraycpy {
public static void main(String[] args) {
String s1[] = {"a","b","c","d","e"};
String s2[] = new String[5];
System.arraycopy(s1, 2, s2, 0, 3);
for (String s11 : s2) {
System.out.print(s11+" ");
}
}
}
//输出:c d e null null
数组的扩容和数组的删除
实际也是数组的拷贝做原理
//删除某个数组元素(本质是数组自身的拷贝)
public static void del() {
String s1[] = {"a","b","c","d","e"};
System.arraycopy(s1, 3, s1, 2, 2);
s1[s1.length -1] = null;
for (String m : s1) {
System.out.print(m+" ");
}
}
//数组扩容(本质是定义一个更大的数组 再把原数组拷贝到新数组内)
public static void extend() {
String s1[] = {"a","b","c","d","e"};
String s2[] = new String[s1.length+5];
System.arraycopy(s1, 0, s2, 0, s1.length);
for (String m : s2) {
System.out.print(m+" ");
}
}
java.util.Arrays类
包含了常用的数组操作,方便开发。Arrays类包含了:排序、查找、填充、打印内容等常见的操作
import java.util.Arrays;
public class Test {
public static void main(String args[]) {
int a[] = { 1, 12 };
Arrays.sort(a); //数组的排序
System.out.println(Arrays.binarySearch(a, 12)); //array里面的二分查找
System.out.println(Arrays.toString(a)); // 打印数组元素的值;
int[] arr2 = new int[5];
Arrays.fill(arr2,2,4, 100); //数组的填充
System.out.println(Arrays.toString(arr2));
}
}
多维数组
声明
public class Test {
public static void main(String[] args) {
//Java中多维数组的声明和初始化应按从低维到高维的顺序进行
int a[][] = new int[3][]; //把数组看成对象存入一维数组
a[0] = new int[2];
a[1] = new int[4];
a[2] = new int[3];
// int a1[][]=new int[][4];非法
}
}
public class TextArrayTab {
public static void main(String[] args) {
//数组存储表格数据
Object[] temp1 = {1000,"H",20,"adc"};
Object[] temp2 = {1001,"G",21,"dc"};
Object[] temp3 = {1002,"F",22,"ac"};
Object tabledata[][] = new Object[3][];
tabledata[0] = temp1;
tabledata[1] = temp2;
tabledata[2] = temp3;
for(Object[] temp: tabledata) {
System.out.println(Arrays.toString(temp));
}
}
}