Caching Java Objects.

Caching Java Objects for faster retrieval needs just two things, override the hashCode method and equals method of the class’s object to be cached. Things that I would consider while overriding the hashCode is a) to use the fields that make the unique key and b) avoid String fields as much as possible. This example illustrates the same.
package test.classCache;
public class ProductDetails {
  private long productId = -1;
  private long productCode = -1;
  private String productName = null;
  private String productDescription = null;
  public long getProductCode() {
    return productCode;
  }
  public void setProductCode(long productCode) {
    this.productCode = productCode;
  }
  public String getProductDescription() {
    return productDescription;
  }
  public void setProductDescription(String productDescription) {
    this.productDescription = productDescription;
  }
  public long getProductId() {
    return productId;
  }
  public void setProductId(long productId) {
    this.productId = productId;
  }
  public String getProductName() {
    return productName;
  }
  public void setProductName(String productName) {
    this.productName = productName;
  }  
  public int hashCode() {
    return Long.valueOf((this.productCode+this.productId)).hashCode();
  }  
  public boolean equals(Object o) {
    ProductDetails pDetsils = (ProductDetailso;
    return ( (this.productCode == pDetsils.productCode&& (this.productId == pDetsils.productId));
  }
}

Java2html

No comments:

Followers