1

I've got something set up, now I want to have a string saved, with an Date attached to it.

private HashMap<String, Date> something = new HashMap<String, Date>();

The problem I'm having is that I only want 1 thing inside this HashMap, so when I put a new String, Date in, the old one gets removed.

I've got this myself by just calling clear before I add one, but then I came on to a different problem:

String current = something.get ????

As you see above, I just want to get the 1 entry inside. Without the date.

Is there a better alternative? Or am I seeing something completely wrong?

MrDikke
  • 121
  • 13

3 Answers3

2

You can use Pair<K,V>:

A convenience class to represent name-value pairs.

// The import statement
import javafx.util.Pair;

Pair<String, Date> something = new Pair<>("string1", new Date());

And you can use

something.getKey() to get the String, & something.getValue() to get the Date.

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • Only problem with this, Pairs can only be set in the statement you gave me above right? But I do need to set it more than once... – MrDikke Jan 28 '16 at 13:22
  • @MrDikke No, it's not `final`; you are free to assign a new instance of Pair to your reference at any point in your program. – Mohammed Aouf Zouag Jan 28 '16 at 13:29
0

You have several possibilities to do that. You could just have a String and a Date variable together with a setter:

private String someString;
private Date someDate;

private void setStringDate(String someString, Date someDate) {
    this.someString = someString;
    this.someDate = someDate;
}

Another possibility is to encapsulate that functionality in a class:

public class StringDate {
    private String someString;
    private Date someDate;

    // setter ... (like above)

    public String getSomeString() {
        return someString;
    }

    public Date getSomeDate() {
        return someDate;
    }
}

Of course, if you need other Data-structures than String and Date you could use Generics on your own class to realize that!

ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
0

It seems something should just be a variable that stores a String,Date pair. If you don't want to define a tiny class for that, or use two variables, you can use a Pair .

Community
  • 1
  • 1
leonbloy
  • 73,180
  • 20
  • 142
  • 190