下面列出了怎么用java.util.RandomAccess的API类实例代码及写法,或者点击链接到github查看源代码。
private static void checkNullElements(final Collection<?> c) {
if (c instanceof RandomAccess && c instanceof List) {
// produce less garbage
final List<?> list = (List<?>) c;
final int size = list.size();
for (int i = 0; i < size; i++) {
if (list.get(i) == null) {
throw new IllegalArgumentException("c contains null values");
}
}
} else {
for (final Object element : c) {
if (element == null) {
throw new IllegalArgumentException("c contains null values");
}
}
}
}
private static void encodeAuthMethodRequest(Socks5InitialRequest msg, ByteBuf out) {
out.writeByte(msg.version().byteValue());
final List<Socks5AuthMethod> authMethods = msg.authMethods();
final int numAuthMethods = authMethods.size();
out.writeByte(numAuthMethods);
if (authMethods instanceof RandomAccess) {
for (int i = 0; i < numAuthMethods; i ++) {
out.writeByte(authMethods.get(i).byteValue());
}
} else {
for (Socks5AuthMethod a: authMethods) {
out.writeByte(a.byteValue());
}
}
}
private static void writeParameters(List<CharSequence> parameters, ByteBuf out) {
if (parameters.isEmpty()) {
return;
}
out.writeByte(SP);
if (parameters instanceof RandomAccess) {
final int sizeMinusOne = parameters.size() - 1;
for (int i = 0; i < sizeMinusOne; i++) {
ByteBufUtil.writeAscii(out, parameters.get(i));
out.writeByte(SP);
}
ByteBufUtil.writeAscii(out, parameters.get(sizeMinusOne));
} else {
final Iterator<CharSequence> params = parameters.iterator();
for (;;) {
ByteBufUtil.writeAscii(out, params.next());
if (params.hasNext()) {
out.writeByte(SP);
} else {
break;
}
}
}
}
private static void checkNullElements(Collection<?> c) {
if (c instanceof RandomAccess && c instanceof List) {
// produce less garbage
List<?> list = (List<?>) c;
int size = list.size();
for (int i = 0; i < size; i++) {
if (list.get(i) == null) {
throw new IllegalArgumentException("c contains null values");
}
}
} else {
for (Object element: c) {
if (element == null) {
throw new IllegalArgumentException("c contains null values");
}
}
}
}
@Override
public void write(ByteBuf byteBuf, Page<User> userPage) {
List<User> userList = userPage.getResult();
byteBuf.writeInt(userPage.getPageNo());
byteBuf.writeInt(userPage.getTotal());
byteBuf.writeInt(userList.size());
if (userList instanceof RandomAccess) {
for (int i = 0; i < userList.size(); i++) {
userSerializer.write(byteBuf, userList.get(i));
}
} else {
for (User user : userList) {
userSerializer.write(byteBuf, user);
}
}
}
public boolean addAll(Iterable<? extends E> c) {
if (c instanceof RandomAccess && c instanceof List<?>)
return addAll((List<? extends E>) c);
if (c instanceof FastCollection<?>)
return addAll((FastCollection<? extends E>) c);
if (c instanceof AEFastCollection<?>)
return addAll((AEFastCollection<? extends E>) c);
boolean modified = false;
for (E e : c)
if (add(e))
modified = true;
return modified;
}
/**
* An implementation of {@link List#lastIndexOf(Object)}.
*/
static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
if (list instanceof RandomAccess) {
return lastIndexOfRandomAccess(list, element);
} else {
ListIterator<?> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
if (Objects.equal(element, listIterator.previous())) {
return listIterator.nextIndex();
}
}
return -1;
}
}
@Override
public boolean addAll(Collection<? extends E> collection) {
ensureCapacity(size() + collection.size());
boolean added = false;
if (collection instanceof ArraySet) {
// Use a code path in SimpleArrayMap which avoids an iterator allocation. It is also optimized
// to run in O(N) time when this.size() == 0.
ArraySet<? extends E> arraySet = (ArraySet) collection;
int oldSize = size();
mMap.putAll(arraySet.mMap);
added = size() != oldSize;
} else if (collection instanceof List && collection instanceof RandomAccess) {
List<? extends E> list = (List) collection;
for (int i = 0, size = list.size(); i < size; ++i) {
added |= add(list.get(i));
}
} else {
for (E value : collection) {
added |= add(value);
}
}
return added;
}
@Override
public boolean containsAll(Collection<?> collection) {
if (collection instanceof List && collection instanceof RandomAccess) {
List<?> list = (List) collection;
for (int i = 0, size = list.size(); i < size; ++i) {
if (!contains(list.get(i))) {
return false;
}
}
} else {
Iterator<?> it = collection.iterator();
while (it.hasNext()) {
if (!contains(it.next())) {
return false;
}
}
}
return true;
}
@Override
public boolean removeAll(Collection<?> collection) {
boolean removed = false;
if (collection instanceof List && collection instanceof RandomAccess) {
// If possible, avoid the iterator allocation inherent in for-each
final List<?> list = (List) collection;
for (int i = 0, size = list.size(); i < size; ++i) {
removed |= remove(list.get(i));
}
} else {
for (Object value : collection) {
removed |= remove(value);
}
}
return removed;
}
/**
* Create a typesafe copy of a raw list.
* @param rawList an unchecked list
* @param type the desired supertype of the entries
* @param strict true to throw a <code>ClassCastException</code> if the raw list has an invalid entry,
* false to skip over such entries (warnings may be logged)
* @return a typed list guaranteed to contain only entries assignable
* to the named type (or they may be null)
* @throws ClassCastException if some entry in the raw list was not well-typed, and only if <code>strict</code> was true
*/
public static <E> List<E> checkedListByCopy(List rawList, Class<E> type, boolean strict) throws ClassCastException {
List<E> l = (rawList instanceof RandomAccess) ? new ArrayList<E>(rawList.size()) : new LinkedList<E>();
Iterator<?> it = rawList.iterator();
while (it.hasNext()) {
Object e = it.next();
try {
l.add(type.cast(e));
} catch (ClassCastException x) {
if (strict) {
throw x;
} else {
LOG.log(Level.WARNING, "Element {0} not assignable to {1}", new Object[] {e, type});
}
}
}
return l;
}
@SuppressWarnings("unchecked")
static <T> void forEachPageEntry(final @NonNull Collection<? extends T> content, final int pageSize, final int page, final @NonNull ObjIntConsumer<? super T> consumer) {
final int size = content.size();
final int start = pageSize * (page - 1);
final int end = pageSize * page;
if(content instanceof List<?> && content instanceof RandomAccess) {
final List<? extends T> list = (List<? extends T>) content;
for(int i = start; i < end && i < size; i++) {
consumer.accept(list.get(i), i);
}
} else {
final Iterator<? extends T> it = content.iterator();
// skip entries on previous pages
for(int i = 0; i < start; i++) {
it.next();
}
for(int i = start; i < end && i < size; i++) {
consumer.accept(it.next(), i);
}
}
}
@Override
public void write(ByteBuf byteBuf, Page<User> userPage) {
List<User> userList = userPage.getResult();
byteBuf.writeInt(userPage.getPageNo());
byteBuf.writeInt(userPage.getTotal());
byteBuf.writeInt(userList.size());
if (userList instanceof RandomAccess) {
for (int i = 0; i < userList.size(); i++) {
userSerializer.write(byteBuf, userList.get(i));
}
} else {
for (User user : userList) {
userSerializer.write(byteBuf, user);
}
}
}
@Override
public void write(ByteBuf byteBuf, Page<User> userPage) {
List<User> userList = userPage.getResult();
byteBuf.writeInt(userPage.getPageNo());
byteBuf.writeInt(userPage.getTotal());
byteBuf.writeInt(userList.size());
if (userList instanceof RandomAccess) {
for (int i = 0; i < userList.size(); i++) {
userSerializer.write(byteBuf, userList.get(i));
}
} else {
for (User user : userList) {
userSerializer.write(byteBuf, user);
}
}
}
/**
* Direct shuffle on the list adapted from JDK java.util.Collections.
* This handles RandomAccess lists.
*
* @param rng Random number generator.
* @param list List.
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private static void shuffleDirectRandomAccess(UniformRandomProvider rng, List<?> list) {
if (list instanceof RandomAccess || list.size() < RANDOM_ACCESS_SIZE_THRESHOLD) {
// Shuffle list in-place
for (int i = list.size(); i > 1; i--) {
swap(list, i - 1, rng.nextInt(i));
}
} else {
// Shuffle as an array
final Object[] array = list.toArray();
for (int i = array.length; i > 1; i--) {
swap(array, i - 1, rng.nextInt(i));
}
// Copy back. Use raw types.
final ListIterator it = list.listIterator();
for (final Object value : array) {
it.next();
it.set(value);
}
}
}
/**
* Shuffles the entries of the given array, using the
* <a href="http://en.wikipedia.org/wiki/Fisher-Yates_shuffle#The_modern_algorithm">
* Fisher-Yates</a> algorithm.
*
* <p>
* Sampling uses {@link UniformRandomProvider#nextInt(int)}.
* </p>
*
* @param <T> Type of the list items.
* @param rng Random number generator.
* @param list List whose entries will be shuffled (in-place).
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static <T> void shuffle(UniformRandomProvider rng,
List<T> list) {
if (list instanceof RandomAccess || list.size() < RANDOM_ACCESS_SIZE_THRESHOLD) {
// Shuffle list in-place
for (int i = list.size(); i > 1; i--) {
swap(list, i - 1, rng.nextInt(i));
}
} else {
// Shuffle as an array
final Object[] array = list.toArray();
for (int i = array.length; i > 1; i--) {
swap(array, i - 1, rng.nextInt(i));
}
// Copy back. Use raw types.
final ListIterator it = list.listIterator();
for (final Object item : array) {
it.next();
it.set(item);
}
}
}
public void addAll(Collection<T> c)
{
if (c instanceof RandomAccess)
{
List list = (List) c;
int size = c.size();
for (int i = 0; i < size; i++)
{
this.put(list.get(i));
}
}
else
{
for (T t : c)
{
this.put(t);
}
}
}
public StoredFeatureSet(String name, List<StoredFeature> features) {
this.name = Objects.requireNonNull(name);
features = Objects.requireNonNull(features);
if (!(features instanceof RandomAccess)) {
features = new ArrayList<>(features);
}
this.features = features;
featureMap = new HashMap<>();
int ordinal = -1;
for (StoredFeature feature : features) {
ordinal++;
if (featureMap.put(feature.name(), ordinal) != null) {
throw new IllegalArgumentException("Feature [" + feature.name() + "] defined twice in this set: " +
"feature names must be unique in a set.");
}
}
}
/**
* An implementation of {@link List#equals(Object)}.
*/
static boolean equalsImpl(List<?> thisList, @Nullable Object other) {
if (other == checkNotNull(thisList)) {
return true;
}
if (!(other instanceof List)) {
return false;
}
List<?> otherList = (List<?>) other;
int size = thisList.size();
if (size != otherList.size()) {
return false;
}
if (thisList instanceof RandomAccess && otherList instanceof RandomAccess) {
// avoid allocation and use the faster loop
for (int i = 0; i < size; i++) {
if (!Objects.equal(thisList.get(i), otherList.get(i))) {
return false;
}
}
return true;
} else {
return Iterators.elementsEqual(thisList.iterator(), otherList.iterator());
}
}
/**
* An implementation of {@link List#indexOf(Object)}.
*/
static int indexOfImpl(List<?> list, @Nullable Object element) {
if (list instanceof RandomAccess) {
return indexOfRandomAccess(list, element);
} else {
ListIterator<?> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (Objects.equal(element, listIterator.next())) {
return listIterator.previousIndex();
}
}
return -1;
}
}
/**
* An implementation of {@link List#lastIndexOf(Object)}.
*/
static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
if (list instanceof RandomAccess) {
return lastIndexOfRandomAccess(list, element);
} else {
ListIterator<?> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
if (Objects.equal(element, listIterator.previous())) {
return listIterator.nextIndex();
}
}
return -1;
}
}
/**
* An implementation of {@link List#indexOf(Object)}.
*/
static int indexOfImpl(List<?> list, @Nullable Object element) {
if (list instanceof RandomAccess) {
return indexOfRandomAccess(list, element);
} else {
ListIterator<?> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (Objects.equal(element, listIterator.next())) {
return listIterator.previousIndex();
}
}
return -1;
}
}
/**
* An implementation of {@link List#lastIndexOf(Object)}.
*/
static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
if (list instanceof RandomAccess) {
return lastIndexOfRandomAccess(list, element);
} else {
ListIterator<?> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
if (Objects.equal(element, listIterator.previous())) {
return listIterator.nextIndex();
}
}
return -1;
}
}
/**
* An implementation of {@link List#subList(int, int)}.
*/
static <E> List<E> subListImpl(final List<E> list, int fromIndex, int toIndex) {
List<E> wrapper;
if (list instanceof RandomAccess) {
wrapper =
new RandomAccessListWrapper<E>(list) {
@Override
public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
} else {
wrapper =
new AbstractListWrapper<E>(list) {
@Override
public ListIterator<E> listIterator(int index) {
return backingList.listIterator(index);
}
private static final long serialVersionUID = 0;
};
}
return wrapper.subList(fromIndex, toIndex);
}
/**
* An implementation of {@link List#indexOf(Object)}.
*/
static int indexOfImpl(List<?> list, @Nullable Object element) {
if (list instanceof RandomAccess) {
return indexOfRandomAccess(list, element);
} else {
ListIterator<?> listIterator = list.listIterator();
while (listIterator.hasNext()) {
if (Objects.equal(element, listIterator.next())) {
return listIterator.previousIndex();
}
}
return -1;
}
}
/**
* An implementation of {@link List#lastIndexOf(Object)}.
*/
static int lastIndexOfImpl(List<?> list, @Nullable Object element) {
if (list instanceof RandomAccess) {
return lastIndexOfRandomAccess(list, element);
} else {
ListIterator<?> listIterator = list.listIterator(list.size());
while (listIterator.hasPrevious()) {
if (Objects.equal(element, listIterator.previous())) {
return listIterator.nextIndex();
}
}
return -1;
}
}
/** Transforms a list, applying a function to each element. */
public static <F, T> List<T> transform(List<F> list,
java.util.function.Function<F, T> function) {
if (list instanceof RandomAccess) {
return new RandomAccessTransformingList<>(list, function);
} else {
return new TransformingList<>(list, function);
}
}
/** Transforms a list, applying a function to each element. */
public static <F, T> List<T> transform(List<F> list,
java.util.function.Function<F, T> function) {
if (list instanceof RandomAccess) {
return new RandomAccessTransformingList<>(list, function);
} else {
return new TransformingList<>(list, function);
}
}
/**
* Creates a {@code List<TSource>} from an {@code Enumerable<TSource>}.
*/
@SuppressWarnings("unchecked")
public static <TSource> List<TSource> toList(Enumerable<TSource> source) {
if (source instanceof List && source instanceof RandomAccess) {
return (List<TSource>) source;
} else {
return source.into(
source instanceof Collection
? new ArrayList<>(((Collection) source).size())
: new ArrayList<>());
}
}
protected void encode(ChannelHandlerContext ctx, List<RequestWithFuture> requestList, ByteBuf buffer)
throws Exception {
if (requestList instanceof RandomAccess) {
for (int i = 0; i < requestList.size(); i++) {
doEncode(buffer, requestList.get(i));
}
} else {
for (RequestWithFuture request : requestList) {
doEncode(buffer, request);
}
}
}