[Java Core] - hashCode method

June 26, 2019 |

hashCode()
       A hash code is a integer number which puts instance of a class into a finite number of categories.
When you override equals(), you are also expected to override hashCode() method because the hashcode is used when storing the object as a key in a maps. the has code was  used in Collection as HashMap, HashTable, HashSet.
There are 4 points when override hashMap().
-  When equals() was override, hashCode must be override too.
-  The result of hashCode must be not change. This mean that you shoudn't include the variable usually change or not unique
-  If equals() return true when called with two objects, Java program call hashCode() on each of those object must return the same result.
- If equals() return false when called with two objects, calling hashCode() on each of those object doesn't have return a different result.

Example: Not Override hashCode()

public class Card {
    private String rank;
    private String suit;
    public Card(String r, String s) {
        if (r == null || s == null) {
            throw new IllegalArgumentException("arg1,arg2 are null.");
        }
       
        rank = r;
        suit = s;
    }

    @Override
    public String toString() {
        return "rank:" + this.rank + " suit: " + this.suit;
    }

    @Override
    public boolean equals(Object obj) {
        if ( !(obj instanceof Card)) return false;
        Card c = (Card) obj;
        return rank.equals(c.rank) && suit.equals(c.suit);
    }
   
}


public class HashCodeTest {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Card card1 = new Card("1", "1");
        Card card2 = new Card("1", "1");
       
        Set<Card> cardList = new HashSet<>();
        cardList.add(card1);
        cardList.add(card2);
       
        System.out.println(cardList);
       
    }
   
}


Result: 
run:
[rank:1 suit: 1, rank:1 suit: 1]
BUILD SUCCESSFUL (total time: 0 seconds)

Example: Override hashCode()
Add block code to Card class
    @Override
    public int hashCode() {
        return rank.hashCode();
    }


Result:
run:
[rank:1 suit: 1]
BUILD SUCCESSFUL (total time: 0 seconds)


Read more…

[Java Design Pattern] [Creational Pattern] - Singleton

June 12, 2019 |
Creational Pattern - Singleton 
Purpose: The singleton ensures that a class only one instance and provides a global point of access to it.

This article show how to use Singletone design pattern.  

CarHelper.java
public class CarHelper {
   
    private static CarHelper _instance = null;

    private int distance;
   
    public static synchronized CarHelper getInstance() {
        if (_instance == null) {
            _instance = new CarHelper();
        }
       
        return _instance;
    }

    public int getDistance() {
        return distance;
    }

    public void setDistance(int distance) {
        this.distance += distance;
    }
}


SingletoneMain.java
public class SingletonMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CarHelper.getInstance().setDistance(10);
        System.out.println(CarHelper.getInstance().getDistance());
       
        CarHelper.getInstance().setDistance(20);
        System.out.println(CarHelper.getInstance().getDistance());
       
        CarHelper.getInstance().setDistance(30);
        System.out.println(CarHelper.getInstance().getDistance());

    }

}


Result:
10
30
60


We can see that each time get instance from CarHelper, it same an instance.

Example: we not allow init Statistics object by constructor.
public class Statistics implements Serializable {

    // Definition for the class instance
    private static volatile Statistics instance = new Statistics();

    private List teams = new ArrayList();

    /**
     * Constructor has been made private so that outside classes do not have
     * access to instantiate more instances of Statistics.
     */
    private Statistics() {
    }

    /**
     * Accessor for the statistics class. Only allows for one instance of the
     * class to be created.
     *
     * @return
     */
    public static Statistics getInstance() {
        synchronized (Statistics.class) {
            if (instance == null) {
                instance = new Statistics();
            }
        }
        return instance;
    }

    /**
     * @return the teams
     */
    public List getTeams() {
        return teams;
    }

    /**
     * @param teams
     *            the teams to set
     */
    public void setTeams(List teams) {
        this.teams = teams;
    }

    protected Object readResolve() {
        return instance;
    }
}

public static void main(String[] args) {
        Statistics a = Statistics.getInstance();
        List<String> team = new ArrayList<String>();
        team.add("Deposit");
        team.add("Channel");
       
        a.setTeams(team);
       
        Statistics b = Statistics.getInstance();
        System.out.println(b.getTeams());
       
       
    }
 
Read more…