2011年11月11日

Java Arrays的用法


package com.java.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test1 {
    public static void main(String[] args) {
      
       int[] array1 = {1,2,3,4,5};
       int[] array2 = {1,2,3,4,5};
       int[] array3 = {2,5,1,4,3};
      
       // 陣列值判斷
       boolean result1 = Arrays.equals(array1, array2);
       boolean result2 = Arrays.equals(array1, array3);
      
       System.out.println(result1);
       System.out.println(result2);
      
       // 排序
       int[] resultArray = array3;
       Arrays.sort(resultArray);
       System.out.println("排序前");
       // 排序前
       for (int i : array3) {
           System.out.print(i+",");
       }
       System.out.println();
       System.out.println("排序後");
       // 排序後
       for (int i : resultArray) {
           System.out.print(i+",");
       }
      
       // 複製陣列
       System.out.println();
       System.out.println("複製陣列");
       int[] copyArray = new int[5];
       System.arraycopy(array1, 0, copyArray, 0, array1.length);
       for (int i : copyArray) {
           System.out.print(i+",");
       }
      
       //
       System.out.println();
       int binarytResult = Arrays.binarySearch(array3, 2);
       System.out.println("二元搜尋結果 " + binarytResult);
      
       // 將陣列值轉為List再透過ArryList變為可變動的陣列
       List<Integer> list = Arrays.asList(1,2,3);
       ArrayList<Integer> list2 = new ArrayList<Integer>(list);
       list2.add(4);
       System.out.println(list2);
      
       // Arrays.fill填滿陣列
       System.out.println();
       int[] fillArray = new int[5];
       Arrays.fill(fillArray, 5);
       for (int i : fillArray) {
           System.out.print(i);
       }
    }
}

沒有留言:

ShareThis