声明:
float[] scores;//提倡,不能直接分配大小
float scores[];
分配内存:
scores = new float[5];
静态初始化:
float[] scores = {1, 2, 3, 4};
动态初始化(不能指定长度,长度隐含在{}中):
float[] scores;
scores = new float[]{1, 2, 3, 4};
public void init(){
float[] scores = new float[5];
for(int i=0;i<scores.length;i++)
scores[i] = float(Math.random()*100);
}
//增强for循环:只能读取,不能修改!!!
int[] arr = {1, 2, 3, 4};
for(int temp:arr)
System.out.println(temp);
静态初始化方法(有大括号)必须在声明的时候使用;
java.util.Arrays类:
- fill()给数组元素赋值;
- sort()对数组元素进行升序排序;
- equals()比较数组;
- binarySearch()对排序好的数组进行查找;
Scanner sc = new Scanner(System.in);
for(int i=0;i<a.length;i++)
a[i] = sc.nextInt();
Arrays.sort(a);
//打乱shuffle
public void shuffle(float[] arr){
for(int i=0;i<arr.length;i++){
int index = (int)(Math.random()*arr.length);
float temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
}
int[] a = {1, 2, 3};
int[] b;
b = a;
System.out.println(b);//浅拷贝,a和b同时指向一个地址
数组的复制:1:使用for循环进行数组复制,2:使用System.arraycopy()复制;
System.arraycopy(src, 0, dest, 0, src.length);
Arrays.fill(arr, 5);
Arrays.fill(arr, 2, 4, 8);//from the 3rd to the 4th
Arrays.sort(arr, 2, 7);//from the 3rd to the 7th
int[] arr2 = arr.clone();
Arrays.equals(arr, arr2);
Arrays.binarySearch(arr, 5);
Java数组的复制Arrays.copyOf()、System.arraycopy()、nums.clone()
- arraycopy是个本地方法,无返回值。
- copyOf()底层调用arraycopy,返回一个数组,代码更加简短,只是自定义数组长度的能力更差了。
- 最简单的方法num2=num.clone()即可返回,该方法默认是一个浅拷贝,但是对于int和String型数组,相当于深拷贝(String[] str={"1","123"},str[0]="2"并没有改变"1"的内容,而是新建了一个String,将str[0]指向这个String而已)
数组属于对象,因而数组作为参数传递时,传递的是数组的引用;
float sum = add(new float[]{2.3f, 3.4f});//use 匿名数组;
//don't use ,可变长参数列表
public static float add(float...arr){}
float sum = add(2.3f, 3.4f);
int[][] score;
score = new int[5][6];
//锯齿形二维数组
int[][] score = new int[2][];
score[0] = new int[3];
score[1] = new int[5];
//静态
int[][] score = {{1}, {2, 2}, {3, 3, 3}};
int[][] scores = new int[4][2];
for(int i=0;i<scores.length;i++)
for(int j=0;j<scores[i].length;j++)
scores[i][j] = (int)(Math.random()*100);
for(int[] i:scores)
for(int j:i)
System.out.println(j);
String:不可修改,不可变长;StringBuffer:可修改,可变长;
不能有子类,提高效率,优化性能;
String s = new String("xxx");
String t = new String(s);
s.length();//Unicode
s.equalsIgnoreCase(t);
s.compareTo(t);//>0:>t; <0:<t;
s.compareToIgnoreCase(t);
s.contains(t);
s.startWith(t);
s.endWith(t);//boolean
s.indexOf(t, 2);//from the 3rd to the end; return index;
s.lastIndexOf(t, 2);
t = s.substring(1);//from the 2nd
t = s.substring(1, 5);
s.trim();//remove space(before and after);
s.concat(t);
s.charAt(5);
s.toLowerCase();
s.toUpperCase();