Java Number Between between(Comparable obj, Comparable from, Comparable to)

Here you can find the source of between(Comparable obj, Comparable from, Comparable to)

Description

Checks if the given object is between the last two parameter values.

License

Open Source License

Parameter

Parameter Description
obj The object to check.
from The lower value to compare.
to The upper value to compare.

Return

true if obj is between from and to.

Declaration

public static boolean between(Comparable obj, Comparable from, Comparable to) 

Method Source Code

//package com.java2s;
/*//from ww w.  j  ava  2s  .c o m
 * Copyright (C) 2003, 2004 by Christian Lauer.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the Free
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * If you didn't download this code from the following link, you should check if
 * you aren't using an obsolete version:
 * http://sourceforge.net/projects/ujac
 */

public class Main {
    /**
     * Checks if the given object is between the last two parameter values.
     *
     * @param obj  The object to check.
     * @param from The lower value to compare.
     * @param to   The upper value to compare.
     * @return true if <code>obj</code> is between <code>from</code> and <code>to</code>.
     */
    public static boolean between(Comparable obj, Comparable from, Comparable to) {
        int compareObjFrom = compare(obj, from);
        int compareObjTo = compare(obj, to);
        return (compareObjFrom >= 0) && (compareObjTo <= 0);
    }

    /**
     * Compares the given values.
     *
     * @param a The object to compare with object b.
     * @param b The object to compare with object a.
     * @return true if the objects are equal or are both null.
     */
    public static int compare(Comparable a, Comparable b) {
        if ((a == null) || (b == null)) {
            if (a == b) {
                return 0;
            }
            if (a == null) {
                return -1;
            }
            return 1;
        }
        return a.compareTo(b);
    }
}

Related

  1. between(T lower, T upper, T value)
  2. between(T subject, T lower, T upper, boolean exclLowerEnd, boolean exclUpperEnd)