免费A级毛片无码专区网站-成人国产精品视频一区二区-啊 日出水了 用力乖乖在线-国产黑色丝袜在线观看下-天天操美女夜夜操美女-日韩网站在线观看中文字幕-AV高清hd片XXX国产-亚洲av中文字字幕乱码综合-搬开女人下面使劲插视频

Java集合精選常見面試題( 六 )

我們寫一個簡單的方法測試以下:
例如:
String[] arr = {"A","B","C","D","E","F"};System.arraycopy(arr ,3,arr,2,2);從下標為3的位置開始復制,復制的長度為2(復制D、E),從下標為2的位置開始替換為D、E
復制后的數(shù)組為:
String[] arr = {"A","B","D","E","E","F"};Arrays.copyOf()源碼
public static int[] copyOf(int[] original,int newLength) {// 申請一個新的數(shù)組int[] copy = new int[newLength];// 調用System.arraycopy,將源數(shù)組中的數(shù)據(jù)進行拷貝,并返回新的數(shù)組System.arraycopy(original,0,copy,0,Math.min(original.length,newLength));return copy;}Copy to clipboardErrorCopied場景:
/**以正確的順序返回一個包含此列表中所有元素的數(shù)組(從第一個到最后一個元素); 返回的數(shù)組的運行時類型是指定數(shù)組的運行時類型 。*/public Object[] toArray() {//elementData:要復制的數(shù)組;size:要復制的長度return Arrays.copyOf(elementData,size);}個人覺得使用 Arrays.copyOf()方法主要是為了給原有數(shù)組擴容,測試代碼如下:
public class ArrayscopyOfTest {public static void main(String[] args) {int[] a = new int[3];a[0] = 0;a[1] = 1;a[2] = 2;int[] b = Arrays.copyOf(a,10);System.out.println("b.length"+b.length);}}結果:
10擴容規(guī)則總結

  1. ArrayList() 初始化長度為零的數(shù)組
  2. ArrayList(int initialCapacity) 會使用指定容量的數(shù)組
  3. public ArrayList(Collection<? extends E> c) 會使用 c 的大小作為數(shù)組容量
  4. add(Object o) 首次擴容為 10,再次擴容為上次容量的 1.5 倍
  5. addAll(Collection c) 沒有元素時,擴容為 Math.max(10, 實際元素個數(shù)),有元素時為 Math.max(原容量 1.5 倍, 實際元素個數(shù))
其中第 4 點必須知道,其它幾點視個人情況而定
Collection 子接口之 Set1. comparable 和 Comparator 的區(qū)別
  • comparable 接口實際上是出自java.lang包 它有一個 compareTo(Object obj)方法用來排序
  • comparator接口實際上是出自 java.util 包它有一個compare(Object obj1,Object obj2)方法用來排序
一般我們需要對一個集合使用自定義排序時,我們就要重寫compareTo()方法或compare()方法,當我們需要對某一個集合實現(xiàn)兩種排序方式,比如一個 song 對象中的歌名和歌手名分別采用一種排序方法的話,我們可以重寫compareTo()方法和使用自制的Comparator方法或者以兩個 Comparator 來實現(xiàn)歌名排序和歌星名排序,第二種代表我們只能使用兩個參數(shù)版的 Collections.sort()
Comparator 定制排序
ArrayList<Integer> arrayList = new ArrayList<Integer>();arrayList.add(-1);arrayList.add(3);arrayList.add(3);arrayList.add(-5);arrayList.add(7);arrayList.add(4);arrayList.add(-9);arrayList.add(-7);System.out.println("原始數(shù)組:");System.out.println(arrayList);// void reverse(List list):反轉Collections.reverse(arrayList);System.out.println("Collections.reverse(arrayList):");System.out.println(arrayList);// void sort(List list),按自然排序的升序排序Collections.sort(arrayList);System.out.println("Collections.sort(arrayList):");System.out.println(arrayList);// 定制排序的用法Collections.sort(arrayList,new Comparator<Integer>() {@Overridepublic int compare(Integer o1,Integer o2) {return o2.compareTo(o1);}});System.out.println("定制排序后:");System.out.println(arrayList);打印結果
原始數(shù)組:[-1,3,3,-5,7,4,-9,-7]Collections.reverse(arrayList):[-7,-9,4,7,-5,3,3,-1]Collections.sort(arrayList):[-9,-7,-5,-1,3,3,4,7]定制排序后:[7,4,3,3,-1,-5,-7,-9]

經(jīng)驗總結擴展閱讀