How to concat two ArrayLists?

后端 未结 7 1301
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 23:29

I have two ArrayLists of equal size. List 1 consists of 10 names and list 2 consists of their phone numbers.

I want to concat the names and number into

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-14 00:14

    for a lightweight list that does not copy the entries, you may use sth like this:

    List mergedList = new ConcatList<>(list1, list2);
    
    
    

    here the implementation:

    public class ConcatList extends AbstractList {
    
        private final List list1;
        private final List list2;
    
        public ConcatList(final List list1, final List list2) {
            this.list1 = list1;
            this.list2 = list2;
        }
    
        @Override
        public E get(final int index) {
            return getList(index).get(getListIndex(index));
        }
    
        @Override
        public E set(final int index, final E element) {
            return getList(index).set(getListIndex(index), element);
        }
    
        @Override
        public void add(final int index, final E element) {
            getList(index).add(getListIndex(index), element);
        }
    
        @Override
        public E remove(final int index) {
            return getList(index).remove(getListIndex(index));
        }
    
        @Override
        public int size() {
            return list1.size() + list2.size();
        }
    
        @Override
        public void clear() {
            list1.clear();
            list2.clear();
        }
    
        private int getListIndex(final int index) {
            final int size1 = list1.size();
            return index >= size1 ? index - size1 : index;
        }
    
        private List getList(final int index) {
            return index >= list1.size() ? list2 : list1;
        }
    
    }
    

    提交回复
    热议问题