JAVA基于Arrays.sort()實現(xiàn)數(shù)組升序和降序
java中對數(shù)組進行排序
使用Array.sort() 這個默認是升序
@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());
需要注意的是 不能使用基本類型(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); } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 不要在HTML中濫用div2. Electron調(diào)用外接攝像頭并拍照上傳實現(xiàn)詳解3. React優(yōu)雅的封裝SvgIcon組件示例4. CSS清除浮動方法匯總5. CSS百分比padding制作圖片自適應(yīng)布局6. TypeScript實現(xiàn)十大排序算法之歸并排序示例詳解7. vue前端RSA加密java后端解密的方法實現(xiàn)8. HTML DOM setInterval和clearInterval方法案例詳解9. HTML5實戰(zhàn)與剖析之觸摸事件(touchstart、touchmove和touchend)10. HTTP協(xié)議常用的請求頭和響應(yīng)頭響應(yīng)詳解說明(學(xué)習(xí))
