001 /*
002 * Java Genetic Algorithm Library (jenetics-1.6.0).
003 * Copyright (c) 2007-2014 Franz Wilhelmstötter
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * 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 *
017 * Author:
018 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
019 */
020 package org.jenetics.internal.util;
021
022 import static java.util.Objects.requireNonNull;
023
024 import java.util.AbstractList;
025 import java.util.RandomAccess;
026
027 /**
028 * @author <a href="mailto:franz.wilhelmstoetter@gmx.at">Franz Wilhelmstötter</a>
029 * @since 1.4
030 * @version 1.5 — <em>$Date: 2013-12-18 $</em>
031 */
032 public class ArrayProxyList<T> extends AbstractList<T>
033 implements RandomAccess
034 {
035
036 protected final ArrayProxy<T> _proxy;
037
038 public ArrayProxyList(final ArrayProxy<T> proxy) {
039 _proxy = requireNonNull(proxy, "ArrayProxy must not be null.");
040 }
041
042 @Override
043 public T get(final int index) {
044 return _proxy.get(index);
045 }
046
047 @Override
048 public int size() {
049 return _proxy._length;
050 }
051
052 @Override
053 public int indexOf(final Object element) {
054 int index = -1;
055 if (element == null) {
056 for (int i = _proxy._start, n = _proxy._end;
057 i < n && index == -1; ++i)
058 {
059 if (_proxy.__get(i) == null) {
060 index = i;
061 }
062 }
063 } else {
064 for (int i = _proxy._start, n = _proxy._end;
065 i < n && index == -1; ++i)
066 {
067 if (element.equals(_proxy.__get(i))) {
068 index = i;
069 }
070 }
071 }
072
073 return index;
074 }
075
076 @Override
077 public boolean contains(final Object element) {
078 return indexOf(element) != -1;
079 }
080
081 @Override
082 public Object[] toArray() {
083 final Object[] array = new Object[size()];
084 for (int i = size(); --i >= 0;) {
085 array[i] = _proxy.uncheckedGet(i);
086 }
087 return array;
088 }
089
090 @SuppressWarnings("unchecked")
091 @Override
092 public <E> E[] toArray(final E[] array) {
093 if (array.length < size()) {
094 final E[] copy = (E[])java.lang.reflect.Array.newInstance(
095 array.getClass().getComponentType(), size()
096 );
097 for (int i = size(); --i >= 0;) {
098 copy[i] = (E)_proxy.uncheckedGet(i);
099 }
100
101 return copy;
102 }
103
104 for (int i = size(); --i >= 0;) {
105 array[i] = (E)_proxy.uncheckedGet(i);
106 }
107 return array;
108 }
109
110 }
|