
org.osgi.util.converter.ListDelegate Maven / Gradle / Ivy
/*
* Copyright (c) OSGi Alliance (2017). All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.osgi.util.converter;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* @author $Id$
*/
class ListDelegate implements List {
private volatile List delegate;
private volatile boolean cloned;
private final ConvertingImpl convertingImpl;
@SuppressWarnings({
"unchecked", "rawtypes"
})
static List forArray(Object arr, ConvertingImpl converting) {
return new ListDelegate(new ArrayDelegate(arr), converting);
}
static List forCollection(Collection object,
ConvertingImpl converting) {
if (object instanceof List) {
return new ListDelegate((List) object, converting);
}
return new ListDelegate(new CollectionDelegate<>(object),
converting);
}
private ListDelegate(List del, ConvertingImpl conv) {
delegate = del;
convertingImpl = conv;
}
// Whenever a modification is made, the delegate is cloned and detached.
@SuppressWarnings("unchecked")
private void cloneDelegate() {
if (cloned) {
return;
} else {
cloned = true;
delegate = new ArrayList((List) Arrays.asList(toArray()));
}
}
@Override
public int size() {
return delegate.size();
}
@Override
public boolean isEmpty() {
return delegate.isEmpty();
}
@Override
public boolean contains(Object o) {
return containsAll(Collections.singletonList(o));
}
@Override
public Iterator iterator() {
return listIterator();
}
@Override
public Object[] toArray() {
return toArray(new Object[size()]);
}
@SuppressWarnings("unchecked")
@Override
public X[] toArray(X[] a) {
int mySize = size();
if (Array.getLength(a) < size()) {
a = (X[]) Array.newInstance(a.getClass().getComponentType(),
mySize);
}
for (int i = 0; i < a.length; i++) {
if (mySize > i) {
a[i] = (X) get(i);
} else {
a[i] = null;
}
}
return a;
}
@Override
public boolean add(T e) {
cloneDelegate();
return delegate.add(e);
}
@Override
public boolean remove(Object o) {
cloneDelegate();
return delegate.remove(o);
}
@Override
public boolean containsAll(Collection< ? > c) {
List
© 2015 - 2025 Weber Informatics LLC | Privacy Policy