Reputation: 49
I would like to set dynamic Date values to the Map<String,Object>
and display that in the UI. I am working on JSF2. Here is my code
private Map<String, Object> selectDates;
{
selectDates = new LinkedHashMap<String, Object>();
selectDates.put("First Date", "111"); //label, value
selectDates.put("Second Date", "222");
}
public Map<String, Object> getSelectDates()
{
return selectDates;
}
I am having a drop down with label "First Date" and "Second Date" , now i have to assign values to these key dynamically. It does not work if i give as below:
private Date exDate;
private Date frontDate;
private Map<String, Object> selectDates;
{
selectDates = new LinkedHashMap<String, Object>();
selectDates.put("First Date", exDate;); //label, value
selectDates.put("Second Date", frontDate;);
}
public Map<String, Object> getSelectDates() {
return selectDates;
}
I tried using private Map<String, Date> selectDates;
but this does not give me value, it gives me null
.
Upvotes: 1
Views: 863
Reputation: 4434
You are using a non - static initalization code block. This code will only be executed when an instance of the containing class is created. Here is what I've got when I am trying to use your code
public class DatesInHash {
private Date exDate;
private Date frontDate;
private Map<String, Object> selectDates;
{
//exDate = new Date();
selectDates = new LinkedHashMap<String, Object>();
selectDates.put("First Date", exDate); //label, value
selectDates.put("Second Date", frontDate);
}
public Map<String, Object> getSelectDates() {
return selectDates;
}
public void doDemo() {
exDate = new Date();
frontDate = new Date();
Map<String, Object> datesMap = getSelectDates();
System.out.println(((Date)datesMap.get("First Date")).toString());
}
public static void main(String[] args) {
DatesInHash dIH = new DatesInHash();
dIH.doDemo();
}
}
When I execute this application I get a null pointer exception because at the moment the object gets constructed the non - static block gets invoked and since your two Date variables are null, it triggers the exception.
However if I uncomment this line of code //exDate = new Date();
, I will work fine and displays a formatted version of the date variable.
Unless you need to use a non - static iniatialization bloc for a very specific reason I suggest that you create a simple initialization method of your map such as
public void initMap() {
selectDates = new LinkedHashMap<String, Object>();
selectDates.put("First Date", exDate); //label, value
selectDates.put("Second Date", frontDate);
}
And it will only be called after you are sure that the two dates are well initialized. If using the non - static block is mandatory then you need to properly initialize your date objects first.
More usefull infos on the use of non static initialization code blocks here and here
Upvotes: 1