Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an arraylist of objects?

I have a class

public class SMS 
{
    public String addr;
    public String body;
    public String type;
    public String timestamp;
}

Now I have made an arrayList of objects

ArrayList<SMS> temp = new ArrayList<SMS>();

I have added the values. Now I want to sort the arrayList with respect to the timestamp.

How do I sort the arrayList in ascending/descending order with respect to the timestamp?

like image 929
airbourne Avatar asked Dec 01 '25 00:12

airbourne


1 Answers

Collections.sort(temp);

will sort a collection of Comparable objects, so class SMS has to implement Comparable<SMS> :

public class SMS implementes Comparable<SMS>
{
    public String addr;
    public String body;
    public String type;
    public String timestamp;

    @Override
    public int compareTo(SMS other) {
       //for instance
       return addr.compareTo( other.addr );
    }
}

It is usually a good practice, when implementing Comparable to also implement equals() and hashcode() so that equality between objects is consistent with their comparison. Also, you should add some protection against null values :

public class SMS implements Comparable<SMS>
{
    public String addr;
    public String body;
    public String type;
    public String timestamp;

    @Override
    public int compareTo(SMS other) {
       //for instance
       if( addr == null ) {
           return Integer.MAX_VALUE;
       }
       return addr.compareTo( other.addr );
    }

    @Override
    public boolean equals(Object other) {
       //for instance
       if( other instanceof SMS ) {
          if( addr == null && ((SMS) other) != null ) {
              return false;
          }
          return addr.equals(((SMS) other).addr);
       } else {
          return false;
       }
       return addr.compareTo( other.addr );
    }

    @Override
    public int hashcode() {
       //for instance
       if( addr == null ) {
           return 0;
       }
       return addr.hashcode();
    }
}
like image 131
Snicolas Avatar answered Dec 03 '25 12:12

Snicolas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!