Compare two object - Android java.lang

Android examples for java.lang:Object

Description

Compare two object

Demo Code

/*//from w  w w  .  j  a  v  a2 s . c o m
 * File: $RCSfile: ObjectUtilities.java,v $
 *
 * Copyright (c) 2009 Kewill,
 *
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information
 * of Kewill ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered
 * into with Kewill.
 */
//package com.java2s;

import java.math.BigDecimal;

public class Main {
    /**
     * Compare two object
     *
     * @param o1 object 1
     * @param o2 object 2
     * @return {@link Comparable#compareTo(Object)}
     */
    @SuppressWarnings("unchecked")
    public static int compareTwoObject(Object o1, Object o2) {
        Class objClass;
        if (o1 == null && o2 == null) {
            return 0;
        } else if (o1 == null) {
            return -1;
        } else if (o2 == null) {
            return 1;
        }
        objClass = o1.getClass();
        if (o1 instanceof Comparable && o2 instanceof Comparable) {
            int result = ((Comparable) o1).compareTo(o2);
            return normalizeResult(result);
        } else if (objClass.getSuperclass() == Number.class) {
            Number n1 = (Number) o1;
            double d1 = n1.doubleValue();
            Number n2 = (Number) o2;
            double d2 = n2.doubleValue();
            if (d1 < d2) {
                return -1;
            } else if (d1 > d2) {
                return 1;
            } else {
                return 0;
            }
        } else if (objClass == Boolean.class) {
            Boolean bool1 = (Boolean) o1;
            boolean b1 = bool1.booleanValue();
            Boolean bool2 = (Boolean) o2;
            boolean b2 = bool2.booleanValue();
            if (b1 == b2) {
                return 0;
            } else if (b1) {
                return 1;
            } else {
                return -1;
            }
        } else if (objClass == BigDecimal.class) {
            BigDecimal n1 = (BigDecimal) o1;
            double d1 = n1.doubleValue();
            BigDecimal n2 = (BigDecimal) o2;
            double d2 = n2.doubleValue();
            if (d1 < d2) {
                return -1;
            } else if (d1 > d2) {
                return 1;
            } else {
                return 0;
            }
        } else {
            String s1 = o1.toString();
            String s2 = o2.toString();
            int result = s1.compareTo(s2);
            return normalizeResult(result);
        }
    }

    private static int normalizeResult(int compareResult) {
        if (compareResult < 0) {
            return -1;
        } else if (compareResult > 0) {
            return 1;
        } else {
            return 0;
        }
    }
}

Related Tutorials