001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.util;
019
020import java.util.Arrays;
021import org.apache.yetus.audience.InterfaceAudience;
022import org.apache.yetus.audience.InterfaceStability;
023
024/**
025 * This class encapsulates a byte array and overrides hashCode and equals so that it's identity is
026 * based on the data rather than the array instance.
027 */
028@InterfaceAudience.Private
029@InterfaceStability.Stable
030public class HashedBytes {
031
032  private final byte[] bytes;
033  private final int hashCode;
034
035  public HashedBytes(byte[] bytes) {
036    this.bytes = bytes;
037    hashCode = Bytes.hashCode(bytes);
038  }
039
040  public byte[] getBytes() {
041    return bytes;
042  }
043
044  @Override
045  public int hashCode() {
046    return hashCode;
047  }
048
049  @Override
050  public boolean equals(Object obj) {
051    if (this == obj) return true;
052    if (obj == null || getClass() != obj.getClass()) return false;
053    HashedBytes other = (HashedBytes) obj;
054    return (hashCode == other.hashCode) && Arrays.equals(bytes, other.bytes);
055  }
056
057  @Override
058  public String toString() {
059    return Bytes.toStringBinary(bytes);
060  }
061}