今天和課程是對昨天課程數組章節的一個補充和JAVA的一些新特性:
數組操作:(以下方法均要導入util包)
1.數組排序sort。
ex:
import java.util.*;
public class Sort{
public static void main(String[] args){
int[] test = {3,4,2,4,5,6,1,23,42,23};
Arrays.sort(test); //進行排序
for(int x:test){
System.out.println(x);
}
}
} //輸出結果:1 2 3 4 4 5 6 23 23 42
2.數組複製copyOf。
ex:
import java.util.*;
public class Err{
public static void main(String[] args){
int[] test = {3,4,2,4,5,6,1,23,42,23};
int[] test1 = new int[test.length];
test1 = Arrays.copyOf(test,test.length); //複製數組
for(int x:test1){
System.out.print(x+" ");
}
}
}
3.數組比較:
ex:
public static void main(String[] args){
int[] a1 = {1,2,34,123};
int[] a2 = {1,2,34,123};
if(a1 == a2){
System.out.println("相等");
}
else{
System.out.println("不相等");
}
//以上的比較(==)是比較地址
if(Arrays.equals(a1,a2)){
System.out.println("相等");
}
else{
System.out.println("不相等");
}
//以上的比較(equals)是內容比較
//最後輸出第一個是不等於,第二個是等於
(PS:原因請看我博客的另一篇文章JAVA基礎數據類型裏的引用類型)
JAVA新特性:
1.可變參數
ex:
public void test(int... args){
//調用test(1,2,3,4,5) 無論傳入幾個參數,都會成爲args數組;
}
2.foreach:關鍵詞爲for,不以數組下標爲標誌
ex:
int[] a = {1,2,3};
for(int x:a){
System.out.println(x);
//foreach會把數組裏每個數都輸出
}
3.文檔提取
javadoc -d doc DocDemo.java //爲DocDemo.java生成一份參考文檔
javadoc -d doc -author -version DocDemo.java //生成的參考文檔有作者和版本信息