001/*-------------------------------------------------------------------------+
002|                                                                          |
003| Copyright 2005-2011 the ConQAT Project                                   |
004|                                                                          |
005| Licensed under the Apache License, Version 2.0 (the "License");          |
006| you may not use this file except in compliance with the License.         |
007| You may obtain a copy of the License at                                  |
008|                                                                          |
009|    http://www.apache.org/licenses/LICENSE-2.0                            |
010|                                                                          |
011| Unless required by applicable law or agreed to in writing, software      |
012| distributed under the License is distributed on an "AS IS" BASIS,        |
013| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
014| See the License for the specific language governing permissions and      |
015| limitations under the License.                                           |
016+-------------------------------------------------------------------------*/
017package org.conqat.lib.commons.equals;
018
019import java.util.Objects;
020
021/**
022 * This class provides utility methods on hash codes, usually used when
023 * overriding {@link Object#hashCode()}.
024 */
025public abstract class HashCodeUtils {
026
027        /** The prime number used when calculating hash codes. */
028        private static final int PRIME = 31;
029
030        /**
031         * Generates a hash code for part of an array. The hash code is calculated
032         * from the hash codes of the given objects. Only objects that lie within
033         * the given start and end index in the array are considered.
034         * 
035         * This method offers a better performance than creating a copy of the array
036         * that only contains the desired elements and then calling
037         * {@link Objects#hashCode(Object)}.
038         */
039        public static int hashArrayPart(Object[] objects, int startInclusive, int endExclusive) {
040                int hashCode = 1;
041                for (int i = startInclusive; i < endExclusive; i++) {
042                        hashCode = hashCode * PRIME + Objects.hashCode(objects[i]);
043                }
044                return hashCode;
045        }
046
047}