Wednesday, 23 November 2022

Get a composite unmodifiable array list from two arrays

Get a composite unmodifiable array list from two arrays such that, you shouldn’t use extra memory (like do not copy the elements into third array etc.,).

 

Find the below working application.

 


CompositeUnmodifiableArrayList.java

package com.sample.app.collections;

import java.util.AbstractList;
import java.util.Collections;
import java.util.List;

public class CompositeUnmodifiableArrayList<E> extends AbstractList<E> {

    private final E[] arr1;
    private final E[] arr2;

    private final int arr1Length;
    private final int arr2Length;

    private CompositeUnmodifiableArrayList(final E[] arr1, final E[] arr2) {
        this.arr1 = arr1;
        this.arr2 = arr2;
        this.arr1Length = arr1.length;
        this.arr2Length = arr2.length;
    }

    @Override
    public E get(int index) {

        if (index < arr1Length) {
            return arr1[index];
        } else if ( (index - arr1Length) < arr2Length) {
            return arr2[index - arr1Length];
        }

        throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());

    }

    @Override
    public int size() {
        return arr1Length + arr2Length;
    }

    public static <E> List<E> toUnmodifiableCompositeList(final E[] arr1, final E[] arr2) {
        if (arr1 == null || arr1.length == 0) {
            return toUnmodifiableList(arr2);
        } else if (arr2 == null || arr2.length == 0) {
            return toUnmodifiableList(arr1);
        } else {
            return new CompositeUnmodifiableArrayList<E>(arr1, arr2);
        }
    }

    private static <E> List<E> toUnmodifiableList(E[] arr) {
        return arr.length == 0 ? Collections.emptyList() : new UnmodifiableArrayList<E>(arr);
    }

    private static class UnmodifiableArrayList<E> extends AbstractList<E> {

        private final E[] arr;
        private final int arrLength;

        UnmodifiableArrayList(E[] arr) {
            this.arr = arr;
            this.arrLength = arr.length;
        }

        @Override
        public E get(int index) {
            if (index >= arr.length) {
                throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size());
            }
            return arr[index];
        }

        @Override
        public int size() {
            return arrLength;
        }
    }
}

 

Output

2
4
6
8
1
3
5
7
11
13

  

You may like

Interview Questions

Collection programs in Java

Array programs in Java

Get the string representation of an Iterable

Convert an Iterable to List in Java

Convert an Iterable to a Set in Java

Get the last element from a collection in Java

Implement stack data structure using List

No comments:

Post a Comment