java數組基本操作


一、數組聲明

  兩種形式(方括號位置放變量前后都可以):

  int arr[ ]; int[ ] arr2; 

二、數組初始化

  數組初始化也有兩種形式,如下(使用new或不使用new):

  int arr[] = new int[]{1, 3, 5, 7, 9};

  int[] arr2 = {2, 4, 6, 8, 10}; 

三、遍歷數組

  遍歷數組可用for/foreach,如下:

   for循環略

   int arr[] = new int[]{1, 3, 5, 7 ,9};

   for (int x: arr) { System.out.print(x + "\t"); } 


四、Arraysfill填充數組(修改數組

  使用Arrays類的靜態方法,需要import包java.util.Arrays,定義了許多重載方法。

  void fill(int[] a, int val)全部填充

  void fill(int[] a, int fromIndex, int toIndex, int val)填充指定索引的元素  左閉右開

 

    int[] arr = new int[]{6,6,6,6,6,6};
    Arrays.fill(arr, 8);                //8,8,8,8,8,8
    Arrays.fill(arr3, 1, 3, 9);    //6,9,9,8,8,8    

 

 

 

五、Arrayssort對數組排序(使用Arrays.調用)

  void sort(int[] a)全部排序    默認升序

  void sort(int[] a, int fromIndex, int toIndex)排序指定索引的元素

int [] array=new int[]{3,7,8,2,1,9};
Arrays.sort(array);    //全排序
Arrays.sort(array,2,5);    //2到5排序

 

六、ArrayscopyOf復制數組

  int[] copyOf(int[] original, int newLength)復制數組,指定新數組長度

  int[] copyOfRange(int[] original, int from, int to)復制數組,指定所復制的原數組的索引

int [] array=new int[]{3,7,8,2,1,9};
array2=Arrays.copyOf(array,3); //新數組的長度為3
array3=Arrays.copyOfRange(array,3,5); //復制第三到五個元素

七、檢查數組中是否包含某一個值

  先使用Arrays.asList()將Array轉換成List<String>,這樣就可以用動態鏈表的contains函數來判斷元素是否包含在鏈表中

String[] stringArray = { "a", "b", "c", "d", "e" };
        boolean b = Arrays.asList(stringArray).contains("a");
        System.out.println(b);

 

八、連接兩個數組(需要下載apache的jar包)

  ArrayUtils是Apache提供的數組處理類庫,其addAll方法可以很方便地將兩個數組連接成一個數組。

int[] intArray = { 1, 2, 3, 4, 5 };
int[] intArray2 = { 6, 7, 8, 9, 10 };
// Apache Commons Lang library
int[] combinedIntArray = ArrayUtils.addAll(intArray, intArray2);

 


九、數組翻轉

  依然用到了萬能的ArrayUtils。
十、從數組中移除一個元素


十一、java打印數組

 Arrays.toString(arr)  

for(int n: arr)   
   System.out.println(n+", ");  

for (int i = 0; i < arr.length; i++) {  
   System.out.print(arr[i] + ", ");  
}  

System.out.println(Arrays.asList(arr));  

Arrays.asList(arr).stream().forEach(s -> System.out.println(s));

 


十二、定位元素位置

  Arrays.binarySearch(str);//有序數組

  Arrays.asList.indexOf(str);

 

 

參考:https://blog.csdn.net/qq_36084640/article/details/79342722


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM