Tedfoo
Tedfoo

Reputation: 173

Java: how do I create getter/setter methods for a hashmap with a custom type?

I have this sparse matrix implementation:

I'm trying to write getter/setter methods for individual elements based on their key, but I'm not sure how to do this with my custom type Coordinates. For example, theMatrix.get(coordinates) (the usual way) doesn't work.

Could someone show me how to do this?

Upvotes: 0

Views: 3081

Answers (1)

David
David

Reputation: 1136

Class coordinate is not accessible outside of your Matrix class. Indeed, its an implementation detail that you don't want to make visible to the end-user. Please check the getters and setters in the example below.

If you still want to make Coordinates class available to the end-user, you wan make it public.

public class Matrix {

    private static class Coordinates
    {

        private int x = 0;
        private int y = 0;
        private int data = 0;

        public Coordinates(final int x, final int y)
        {
            this.x = x;
            this.y = y;
            data = ((x + "") + (y + "")).hashCode();
        }

        @Override
        public boolean equals(final Object obj)
        {
            if (obj instanceof Coordinates)
            {
                Coordinates Coordinates = (Coordinates) obj;
                return ((x == Coordinates.x) && (y == Coordinates.y));
            }
            else
            {
                return false;
            }
        }

        @Override
        public int hashCode()
        {
            return data;
        }
    }

    private int numrows;
    private int numcolumns;
    private HashMap<Coordinates, Double> theMatrix;

    public Matrix(final int numrows, final int numcolumns)
    {
        this.numrows = numrows;
        this.numcolumns = numcolumns;
    }

    public Matrix(HashMap<Coordinates, Double> matrixdata)
    {
        theMatrix = new HashMap<Coordinates, Double>(matrixdata);
    }

    public Double get(int row, int col, double defaultValue)
    {
        Double ret = theMatrix.get(new Coordinates(row, col));
        return ret != null ? ret : defaultValue;
    }

    public void set(int row, int col, Double value)
    {
        theMatrix.put(new Coordinates(row, col),  value);
    }
}

Upvotes: 2

Related Questions