net.pernek.WordPair.java Source code

Java tutorial

Introduction

Here is the source code for net.pernek.WordPair.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package net.pernek;

import java.util.Arrays;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

/**
 *
 * @author Igor Pernek <igor@pernek.net>
 */
public class WordPair {

    private String keyword1;
    private String keyword2;
    private String topic;

    public WordPair(String keyword1, String keyword2, String topic) {
        this.keyword1 = keyword1;
        this.keyword2 = keyword2;
        this.topic = topic;
    }

    public String getKeyword2() {
        return keyword2;
    }

    public String getKeyword1() {
        return keyword1;
    }

    public String getTopic() {
        return topic;
    }

    @Override
    public boolean equals(Object obj) {
        if (!(obj instanceof WordPair)) {
            return false;
        }
        if (obj == this) {
            return true;
        }

        WordPair rhs = (WordPair) obj;

        // order doesn't matter
        return topic == rhs.topic && ((keyword1 == rhs.keyword1 && keyword2 == rhs.keyword2)
                || (keyword1 == rhs.keyword2 && keyword2 == rhs.keyword1));
    }

    @Override
    public int hashCode() {
        // to get order invariant representation first order
        // the keywords alphabetically
        String[] keywords = { keyword1, keyword2 };
        Arrays.sort(keywords);

        return new HashCodeBuilder(17, 31).append(keywords[0]).append(keywords[1]).append(topic).toHashCode();
    }

    @Override
    public String toString() {

        return keyword1.compareTo(keyword2) < 0 ? String.format("(%s, %s, %s)", keyword1, keyword2, topic)
                : String.format("(%s, %s, %s)", keyword2, keyword1, topic);
    }
}