Sync multiple source ArrayLists into single target list

隐身守侯 提交于 2019-12-24 02:23:42

问题


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.


回答1:


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.




回答2:


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());
  }
}


来源:https://stackoverflow.com/questions/3492786/sync-multiple-source-arraylists-into-single-target-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!