Tuesday, May 27, 2014

Create ConcurrentHashmap with a Bean as Key (in Spring Project)

Removed

Step 1: Create the Bean Key:

In our case, the Key is a Bean. Normally it should be an immutable, but as I am working with Spring and it is difficult to use immutable beans, I have created a normal bean.


Step 2: Override Equal and HashCode:


Using eclipse, you can generate source code for the hashcode and equal. So you need just to right-clic -> Source -> Generate Hash


So the Bean which will be the Key (here it is called User.java) is :

package main.org.qmic.nr.beans;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

@Component
@Scope("singleton")
public class User {

    String enterprise;
    String name;
    
    
    public User() {
        super();
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result
                + ((enterprise == null) ? 0 : enterprise.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }


    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        User other = (User) obj;
        if (enterprise == null) {
            if (other.enterprise != null)
                return false;
        } else if (!enterprise.equals(other.enterprise))
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    
    public User(String enterprise, String name) {
        super();
        this.enterprise = enterprise;
        this.name = name;
    }

    public String getEnterprise() {
        return enterprise;
    }


    public void setEnterprise(String enterprise) {
        this.enterprise = enterprise;
    }

    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }   
}



Step3: Declare the ConcurrentHashMap


private final Map<Device, LatestInfo> latestInfoCache = new ConcurrentHashMap<Device, LatestInfo>();


That's all :)

1 comment :

  1. This comment has been removed by a blog administrator.

    ReplyDelete

Articles les plus consultés