java.util.RandomAccess Java Examples

The following examples show how to use java.util.RandomAccess. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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());
  }
}
 
Example #2
Source File: Socks5ClientEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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());
        }
    }
}
 
Example #3
Source File: KVStateOutputList.java    From sofa-jraft with Apache License 2.0 6 votes vote down vote up
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");
            }
        }
    }
}
 
Example #4
Source File: AEFastCollection.java    From aion-germany with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example #5
Source File: SmtpRequestEncoder.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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;
            }
        }
    }
}
 
Example #6
Source File: RecyclableArrayList.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
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");
            }
        }
    }
}
 
Example #7
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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;
         }
}
 
Example #8
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: UserPageSerializer.java    From turbo-rpc with Apache License 2.0 6 votes vote down vote up
@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);
		}
	}
}
 
Example #10
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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;
         }
}
 
Example #11
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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;
         }
}
 
Example #12
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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;
         }
}
 
Example #13
Source File: ArraySet.java    From litho with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #14
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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;
         }
}
 
Example #15
Source File: ArraySet.java    From litho with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #16
Source File: StoredFeatureSet.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
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.");
        }
    }
}
 
Example #17
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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;
         }
}
 
Example #18
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * 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;
         }
}
 
Example #19
Source File: FullUniqueIndex.java    From reladomo with Apache License 2.0 6 votes vote down vote up
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);
        }
    }
}
 
Example #20
Source File: ListSampler.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #21
Source File: ListShuffleBenchmark.java    From commons-rng with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #22
Source File: UserPageSerializer.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
@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);
		}
	}
}
 
Example #23
Source File: UserPageSerializer.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
@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);
		}
	}
}
 
Example #24
Source File: Paginator.java    From adventure with MIT License 6 votes vote down vote up
@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);
    }
  }
}
 
Example #25
Source File: NbCollections.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #26
Source File: ArraySet.java    From litho with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #27
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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);
}
 
Example #28
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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());
         }
}
 
Example #29
Source File: AbstractProtobufList.java    From play-store-api with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean equals(Object o) {
  if (o == this) {
    return true;
  }
  if (!(o instanceof List)) {
    return false;
  }
  // Handle lists that do not support RandomAccess as efficiently as possible by using an iterator
  // based approach in our super class. Otherwise our index based approach will avoid those
  // allocations.
  if (!(o instanceof RandomAccess)) {
    return super.equals(o);
  }

  List<?> other = (List<?>) o;
  final int size = size();
  if (size != other.size()) {
    return false;
  }
  for (int i = 0; i < size; i++) {
    if (!get(i).equals(other.get(i))) {
      return false;
    }
  }
  return true;
}
 
Example #30
Source File: Lists.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Returns a reversed view of the specified list. For example, {@code
 * Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3,
 * 2, 1}. The returned list is backed by this list, so changes in the returned
 * list are reflected in this list, and vice-versa. The returned list supports
 * all of the optional list operations supported by this list.
 *
 * <p>The returned list is random-access if the specified list is random
 * access.
 *
 * @since 7.0
 */


public static <T> List<T> reverse(List<T> list) {
  if (list instanceof ImmutableList) {
    return ((ImmutableList<T>) list).reverse();
  } else if (list instanceof ReverseList) {
    return ((ReverseList<T>) list).getForwardList();
  } else if (list instanceof RandomAccess) {
    return new RandomAccessReverseList<T>(list);
  } else {
    return new ReverseList<T>(list);
  }
}