JAVA基于Arrays.sort()實(shí)現(xiàn)數(shù)組升序和降序
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); } }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JavaWeb Servlet中url-pattern的使用2. ASP中格式化時(shí)間短日期補(bǔ)0變兩位長(zhǎng)日期的方法3. asp知識(shí)整理筆記4(問(wèn)答模式)4. 怎樣才能用js生成xmldom對(duì)象,并且在firefox中也實(shí)現(xiàn)xml數(shù)據(jù)島?5. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁(yè)6. ASP實(shí)現(xiàn)加法驗(yàn)證碼7. XML解析錯(cuò)誤:未組織好 的解決辦法8. 小技巧處理div內(nèi)容溢出9. js的一些潛在規(guī)則使用分析10. ASP刪除img標(biāo)簽的style屬性只保留src的正則函數(shù)
