001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.jexl3.internal.introspection;
018
019import java.lang.reflect.Array;
020import java.util.AbstractList;
021import java.util.RandomAccess;
022
023/**
024 * A class that wraps an array within an AbstractList.
025 * <p>
026 * It overrides some methods because introspection uses this class a a marker for wrapped arrays; the declared class
027 * for these method is thus ArrayListWrapper.
028 * The methods are get/set/size/contains and indexOf because it is used by contains.
029 * </p>
030 */
031public class ArrayListWrapper extends AbstractList<Object> implements RandomAccess {
032    /** the array to wrap. */
033    private final Object array;
034
035    /**
036     * Create the wrapper.
037     * @param anArray {@link #array}
038     */
039    public ArrayListWrapper(final Object anArray) {
040        if (!anArray.getClass().isArray()) {
041            throw new IllegalArgumentException(anArray.getClass() + " is not an array");
042        }
043        this.array = anArray;
044    }
045
046    @Override
047    public Object get(final int index) {
048        return Array.get(array, index);
049    }
050
051    @Override
052    public Object set(final int index, final Object element) {
053        final Object old = Array.get(array, index);
054        Array.set(array, index, element);
055        return old;
056    }
057
058    @Override
059    public int size() {
060        return Array.getLength(array);
061    }
062
063    @Override
064    public int indexOf(final Object o) {
065        final int size = size();
066        if (o == null) {
067            for (int i = 0; i < size; i++) {
068                if (get(i) == null) {
069                    return i;
070                }
071            }
072        } else {
073            for (int i = 0; i < size; i++) {
074                if (o.equals(get(i))) {
075                    return i;
076                }
077            }
078        }
079        return -1;
080    }
081
082    @Override
083    public boolean contains(final Object o) {
084        return indexOf(o) != -1;
085    }
086}