22 August 2011

Control the appearance of null objects when sorting a collections

SA,

In Java, if you have a list of object and need to order this list.. you have to implement either java.lang.Comparable or java.util.Comporator..

Here's a simple Java class that we need to order it:


  1. public class Param implements Comparable<Param> 
  2. {
  3.     int paramNo;
  4.     String value;
  5.     
  6.     public int compareTo(Param o)
  7.     {
  8.         if (o == null)
  9.             return -1;
 10.         return new Integer(this.paramNo).compareTo(o.paramNo);    // thanks to autoboxing
 11.     }
 12. 
 13.     public String toString()
 14.     {
 15.         return "Param [paramNo=" + paramNo + ", value=" + value + "]";
 16.     }
 17. }

The point here is in the `compareTo` method in the line:

if (o == null) return -1;

This means if the parameter is null, move it to the bottom of the list..

2 comments:

علاء الصالحي said...

حلو جداً
بس في مشكلة كبيرة في الكابتشا تبعت جوجل صعبة جداً

mhewedy said...

المشكله إن أصلا في وقت من الأوقات كان بيجيلى تعليقات سبام كتير حتى و الكابتشا دي موجوده ...