close
Blogtrottr
海芋小站
提供實用軟體教學,介紹有趣網站及資訊,豐富電腦人生 
Kinvey Strategy eBook

Kinvey answers 7 critical questions about creating your mobile strategy and technology policies. See our answers in this free eBook.
From our sponsors
thumbnail [Java] 如何在 ArrayList 中以物件的特定條件做排序?
Aug 9th 2013, 18:46, by 張海芋


ArrayList 是 Java 一個很常用的物件,而這個物件其實可以就像是 c++ 中的「vector」,可以讓你無窮無盡地增加「物件」陣列長度,而且輕易操作,而相關的操作可以看一下海芋之前寫的「ArrayList 筆記」。

而 ArrayList 僅能增加「物件」長度,問題來了,並非每個物件都是「Integer」、「Double」這種好判斷的物件,舉例來說,我們要使用的物件,有可能是學生的基本資料,我們想要依學生的年齡做排序,而並非以學生的姓名做排序,這時我們該怎麼做呢?

在解釋怎麼做之前,我們先來建一個「學生資料」的相關物件。

public class StudentData
{
   public int  ID      = 0;
   public String Name   = null;
   public int  Age   = 0;
}

而假設,我們有一個 ArrayList 存的內容是「學生資料」,如下面的範例。
ArrayList<studentdata> m_data = new ArrayList<studentdata>();

再假設,這個 ArrayList 已經有許多筆學生的資料,那麼我們如何以「學生資料中的Age欄位」,來針對這個 ArrayList 做排序呢?答案很簡單,只要在排序時new一個「Comparator」這個元件就好了,而以下為範例程式碼。
Collections.sort(m_data, new Comparator<studentdata>(){
 @Override
 public int compare(StudentData o1, StudentData o2) {
  return o1.Age - o2.Age;
 }   
});

講到這裡,這個程式已經講解完畢,希望對你有幫助囉!
覺得這篇文章實用嗎?請按讚來分享給更多好朋友知道唷!
喜歡本站的文章嗎?歡迎透過以下方式追蹤本站
版權說明
本文章發佈於海芋小站,內容僅歡迎「部份」引用,引用時請註明出處及原文連結,謝謝。
若圖像無法顯示,可能因流量太大,敬請重新整理或透過留言與我回報,也歡迎「訂閱」本站文章喔,感恩!!
Related Posts with Thumbnails

This entry passed through the Full-Text RSS service — if this is your content and you're reading it on someone else's site, please read the FAQ at fivefilters.org/content-only/faq.php#publishers. Five Filters recommends: 'You Say What You Like, Because They Like What You Say' - http://www.medialens.org/index.php/alerts/alert-archive/alerts-2013/731-you-say-what-you-like-because-they-like-what-you-say.html

You are receiving this email because you subscribed to this feed at blogtrottr.com.

If you no longer wish to receive these emails, you can unsubscribe from this feed, or manage all your subscriptions
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 xals2q 的頭像
    xals2q

    2015花千骨線上看tv 2016花千骨 花千骨線上看drama q 花千骨線上看drama 仙俠奇緣之花千骨線上看 花千骨線上看tv543 電視劇花千骨線上看 花千骨線上看第一集

    xals2q 發表在 痞客邦 留言(0) 人氣()