tags:

views:

68

answers:

2

Hi,

There is a requirement to load a list of items(ArrayList) from two different tables. Due to complex Hibernate mapping, they can not be loaded as one ArrayList. So they are loaded separately by two different Hibernate bags in the class definition. When I use them I'd like to combine into single list. So I am thinking about writing a function as follows,

private List<Item> combinedList = new ArrayList<Item>();

public List<Item> getCombinedList()
{
   combinedList.clear();
   combinedList.addAll(getList1());
   combinedList.addAll(getList2());
   return combinedList;
}

getCombinedList() will be used to display the items and used in other read-only operations. Any delete or modify or add operations will still be executed in List1 and List2 (Because it will be handled by Hibernate).

My question is how can I efficiently sync getCombinedList() with source lists when there is a change?

Update: Calling getCombinedList() every time to get the latest items is inefficient. I am looking for a way to sync the underlying data structure combinedList.

+3  A: 

You'll have to write your own implementation of a list that will be initialized with the two lists and delegate all method execution to both of them securing mutation operations.

Boris Pavlović
+1  A: 

You could create a subclass of AbstractList that delegates to the two separate lists.

public class CombinedList<E> extends AbstractList<E> {
  public CombinedList(List<E> list1, List<E> list2) {
    this.list1 = list1;
    this.list2 = list2;
  }
  List<E> list1;
  List<E> list2;
  public E get(int i) {
    return (i < list1.size()) ? list1.get(i) : list2.get(i - list1.size());
  }
  public boolean add(E e) {
    return list2.add(e);
  }
  public E remove(int i) {
    return (i < list1.size()) ? list1.remove(i) : list2.remove(i - list1.size());
  }
}
Jared Levy