local.laer.app.knapsack.domain.ImmutablePosition.java Source code

Java tutorial

Introduction

Here is the source code for local.laer.app.knapsack.domain.ImmutablePosition.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 local.laer.app.knapsack.domain;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.Objects;

/**
 *
 * @author Lars Eriksson (larsq.eriksson@gmail.com)
 */
@JsonInclude(JsonInclude.Include.ALWAYS)
public class ImmutablePosition implements Position {

    private final int row;
    private final int col;

    @JsonCreator
    public ImmutablePosition(@JsonProperty("row") int row, @JsonProperty("col") int col) {
        this.row = row;
        this.col = col;
    }

    @Override
    @JsonProperty("col")
    public int getCol() {
        return col;
    }

    @Override
    @JsonProperty("row")
    public int getRow() {
        return row;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == this || obj == null) {
            return obj == this;
        }

        if (!Objects.equals(getClass(), obj.getClass())) {
            return false;
        }

        ImmutablePosition other = getClass().cast(obj);

        return col == other.col && row == other.row;
    }

    @Override
    public int hashCode() {
        return Objects.hash(col, row);
    }

    @Override
    public String toString() {
        return String.format("[%s:%s]", row, col);
    }

    public static ImmutablePosition of(int row, int col) {
        return new ImmutablePosition(row, col);
    }

    public static ImmutablePosition of(Position position) {
        return new ImmutablePosition(position.getRow(), position.getCol());
    }
}