Is it a waste of resources with a single element?

2

I have a map with another map in it like the following:

Map<Integer, Map<String, Double>>

However the second map will always have only one element, so I think I'm wasting memory because at the end of the account a map is a list and it is practically a list that will always have an element, although I also think that if it only has one element only occupies the necessary memory for that single element, the question is this: Am I wasting memory? Is there a more optimal way to do what I want? everything would be easier if there was a map with two values.

    
asked by gibran alexis moreno zuñiga 14.03.2017 в 16:56
source

1 answer

3

By your description, it sounds to me that what you really want is that the value of your map contains 2 values. In fact, the fact that you use a Map for this seems an abuse of its function and it is also true that there will be a certain degree of waste.

The correct way to do this is to define a class for that purpose instead of using another map.

Example (adjust the names according to your need):

public class MiTuple {
    private String miString;
    private Double miDouble;

    public MiTuple(String miString, Double miDouble) {
        this.miString = miString;
        this.miDouble = miDouble;
    }

    public String getMiString() {
        return this.miString;
    }

    public Double getMiDouble() {
        return this.miDouble;
    }
}

In this way, you can define your map in a more usual way without "waste", but with all the data you need:

Map<Integer, MiTuple>

... or, as you comment @ Awes0meM4n, and as you can find in this answer , you can create a class equivalent using generic to represent 2 values of any type. This would allow you to recover the same class for different situations:

public class Tuple<X, Y> { 
  public final X x; 
  public final Y y; 
  public Tuple(X x, Y y) { 
    this.x = x; 
    this.y = y; 
  } 
}

In this case, you would define your map in the following way:

Map<Integer, Tuple<String, Double>>
    
answered by 14.03.2017 / 17:02
source