溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

JAVA基于Arrays.sort()如何實(shí)現(xiàn)數(shù)組升序和降序

發(fā)布時(shí)間:2020-07-17 11:48:57 來(lái)源:億速云 閱讀:358 作者:小豬 欄目:編程語(yǔ)言

小編這次要給大家分享的是JAVA基于Arrays.sort()如何實(shí)現(xiàn)數(shù)組升序和降序,文章內(nèi)容豐富,感興趣的小伙伴可以來(lái)了解一下,希望大家閱讀完這篇文章之后能夠有所收獲。

java中對(duì)數(shù)組進(jìn)行排序

使用Array.sort() 這個(gè)默認(rèn)是升序

@Test
  public void index4(){
    int scores[] = new int[]{1,2,3,89,4};
    Arrays.sort(scores);
    for (int i:scores
    ) {
      System.out.println(i);
    }
  }

如果想降序怎么辦呢?

使用:Arrays.sort(scores,Collections.reverseOrder());

需要注意的是 不能使用基本類(lèi)型(int,double, char),如果是int型需要改成Integer,float要改成Float

例子:

@Test
  public void index5(){
    Integer scores[] = {1,2,3,89,4};
    Arrays.sort(scores,Collections.reverseOrder());
    for (Integer i:scores
    ) {
      System.out.println(i);
    }
  }

如果得到的是int數(shù)組,怎么辦,需要先轉(zhuǎn)換一下

@Test
  public void index6(){
    int scores[] = new int[]{1,2,3,89,4};
    Integer newScores[] = new Integer [5];
    for(int i=0;i<scores.length;i++){
      newScores[i]= new Integer(scores[i]);
    }

    Arrays.sort(newScores,Collections.reverseOrder());
    for (Integer i:newScores
    ) {
      System.out.println(i);
    }
  }

看完這篇關(guān)于JAVA基于Arrays.sort()如何實(shí)現(xiàn)數(shù)組升序和降序的文章,如果覺(jué)得文章內(nèi)容寫(xiě)得不錯(cuò)的話(huà),可以把它分享出去給更多人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI