数组的拷贝
System类里也包含了一个static void arraycopy(object src,int srcpos,object dest, int destpos,int length)方法,该方法可以将src数组里的元素值赋给dest数组的元素,其中srcpos指定从src数组的第几个元素开始赋值,length参数指定将src数组的多少个元素赋给dest数组的元素。
String[] s = {"Mircosoft","IBM","Sun","Oracle","Apple"};
String[] sBak = new String[6];
System.arraycopy(s,0,sBak,0,s.length);
数组的排序
int[] a = {1,2,323,23,543,12,59};
System.out.println(Arrays.toString(a));
Arrays.sort(a);
System.out.println(Arrays.toString(a));
/*
结果:
[1, 2, 323, 23, 543, 12, 59]
[1, 2, 12, 23, 59, 323, 543]
*/
如果数组元素是引用类型,那么需要怎么做呢?(今天先不讲!后面讲容器时再讲!)
public class Test{
public static void main(String[] args) {
Man[] msMans = {new Man(3,"a"),new Man(60,"b"),new Man(2,"c")};
Arrays.sort(msMans);
System.out.println(Arrays.toString(msMans));
}
}
class Man implements Comparable {
int age;
int id;
String name;
public Man(int age, String name) {
super();
this.age = age;
this.name = name;
}
public String toString(){
return this.name;
}
public int compareTo(Object o) {
Man man = (Man) o;
if(this.age<man.age){
return -1;
}
if(this.age>man.age){
return 1;
}
return 0;
}
}
小结
- 打印数组(java.util.Arrays)
int[] a = {1,2};
System.out.println(a); //[I@35ce36
System.out.println(Arrays.toString(a)); //[1, 2]
- 二分法查找
int[] a = {1,2,323,23,543,12,59};
Arrays.sort(a); //使用二分法查找,必须先对数组进行排序
System.out.println("该元素的索引:"+Arrays.binarySearch(a, 12));
- 复制
//一般用System. arraycopy
- 填充
Arrays.fill(a, 2, 4, 100); //将2到4索引的元素替换为100
增强for循环
JDK5.0后增加的,一般用于读取数组或集合中所有的元素!
String[] ss = {"aa","bbb","ccc","ddd"};
for (int i = 0; i < ss.length; i++) {
String temp = ss[i];
System.out.println(temp);
}
for (String temp : ss) {
System.out.println(temp);
}
命令行参数
public class TestArgs {
public static void main(String[] args) {
for (int i=0; i<args.length;i++ ) {
System.out.println("args[" + i + "] = " + args[i]);
}
}
}
//运行程序Test13_1.java
java Test lisa bily “Mr Brown”
//输出结果:
args[0] = lisa
args[1] = bily
args[2] = Mr Brown
- eclipse里如何使用?