All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.getperka.cli.ref.IdentityWeakReference Maven / Gradle / Ivy

There is a newer version: 1.18
Show newest version
/*
 * #%L
 * Common Language Idioms
 * %%
 * Copyright (C) 2012 Perka Inc.
 * %%
 * 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.
 * #L%
 */
package com.getperka.cli.ref;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

/**
 * A WeakReference that can be used for simple object-identity comparisons of its referent.
 * 
 * @param  the type of data stored in the reference
 */
public class IdentityWeakReference extends WeakReference {
  private final int hashCode;

  public IdentityWeakReference(T referent) {
    super(referent);
    hashCode = System.identityHashCode(referent);
  }

  public IdentityWeakReference(T referent, ReferenceQueue queue) {
    super(referent, queue);
    hashCode = System.identityHashCode(referent);
  }

  @Override
  public final boolean equals(Object obj) {
    // The reference is equal to itself
    if (this == obj) {
      return true;
    }
    if (!(obj instanceof IdentityWeakReference)) {
      return false;
    }
    T referent = get();
    if (referent == null) {
      return false;
    }
    return referent == ((IdentityWeakReference) obj).get();
  }

  @Override
  public final int hashCode() {
    return hashCode;
  }

  @Override
  public String toString() {
    T obj = get();
    return obj == null ? "" : obj.toString();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy