Feb 16, 2012

List of Lists

Task: to order input data according 2 integer keys.
Example: we have bunch of options. Options have indexes and legs. Legs have indexes and other useful information.
Question: how to extract one type of information from legs?
Answer:
...
private final List<List<FinDate>> expiryDateByOptionAndLeg;
expiryDateByOptionAndLeg = new ArrayList<List<FinDate>>(size){
...
@Override
public List<
FinDate> get(int index) { 
 List<
FinDate> rez = null;
  rez = super.get(index);
  if(rez == null) {
   rez = new ArrayList<
FinDate>(2);
   add(index, rez);
  }
  return rez;
}
};
...
  expiryDateByOptionAndLeg.get(optionsIndex).set(legIndex, expiryDate);


Answer: To use approach suggested in ThreadLocal class javadocs. In this way we receive clear 2-indeger index without need to create list in business code. Similar approach could be applied to Maps.
It's simpler than creating  separate business object and still readable and expressive.

No comments: