集册 Java实例教程 比较一个以上可比较对象的方法。

比较一个以上可比较对象的方法。

欢马劈雪     最近更新时间:2020-01-02 10:19:05

497
比较一个以上可比较对象的方法。

/*

 * Copyright 2014 Lukas Benda <lbenda at lbenda.cz>.

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */
 /* 
  来自 
 *n  o  w  j  a  v  a . c o m*/

//package com.nowjava;


public class Main {

    /** Compare method for more then one object. If the first object is equal (or both are null)

     * then is compare next item. If both object in arra is null then is equal, if one isn't null then is greater. */

    public static int compareArrayNull(Comparable[] o1, Comparable[] o2) {

        if (o1 == null) {

            throw new NullPointerException("Parameter o1 is null");

        }

        if (o2 == null) {

            throw new NullPointerException("Parameter o2 is null");

        }

        if (o1.length != o2.length) {//来 自 n o w    j a v a  . c o m

            throw new IllegalArgumentException(

                    "The parameter o1 and o2 have different length");

        }

        for (int i = 0; i < o1.length; i++) {

            if (!nullEquals(o1[i], o2[i])) {

                if (o1[i] == null) {

                    return -1;

                } else if (o2[i] == null) {

                    return 1;

                }

                if (!o1[i].equals(o2[i])) {

                    return o1[i].compareTo(o2[i]);

                }

            }

        }

        
展开阅读全文