001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.internal; 014 015/** 016 * Utility class for generating integer hash codes. 017 * 018 * <p> 019 * General usage: 020 * <p class='bcode'> 021 * int hashCode = new HashCode().add("foobar").add(myobject).add(123).get(); 022 * </p> 023 */ 024public class HashCode { 025 026 private int hashCode = 1; 027 028 /** 029 * Create a new HashCode object. 030 * 031 * @return A new HashCode object. 032 */ 033 public static final HashCode create() { 034 return new HashCode(); 035 } 036 037 /** 038 * Hashes the hashcode of the specified object into this object. 039 * 040 * @param o The object whose hashcode will be hashed with this object. 041 * @return This object (for method chaining). 042 */ 043 public HashCode add(Object o) { 044 o = unswap(o); 045 add(o == null ? 1 : o.hashCode()); 046 return this; 047 } 048 049 /** 050 * Hashes the hashcode into this object. 051 * 052 * <p> 053 * The formula is simply <code>hashCode = 31*hashCode + i;</code> 054 * 055 * @param i The hashcode to hash into this object's hashcode. 056 * @return This object (for method chaining). 057 */ 058 public HashCode add(int i) { 059 hashCode = 31*hashCode + i; 060 return this; 061 } 062 063 /** 064 * Return the calculated hashcode value. 065 * 066 * @return The calculated hashcode. 067 */ 068 public int get() { 069 return hashCode; 070 } 071 072 /** 073 * Converts the object to a normalized form before grabbing it's hashcode. 074 * 075 * <p> 076 * Subclasses can override this method to provide specialized handling (e.g. converting numbers to strings so that 077 * <code>123</code> and <js>"123"</js> end up creating the same hashcode.) 078 * 079 * <p> 080 * Default implementation does nothing. 081 * 082 * @param o The object to normalize before getting it's hashcode. 083 * @return The normalized object. 084 */ 085 protected Object unswap(Object o) { 086 return o; 087 } 088}