java.util.ArrayList.subList()方法的使用及代码示例

x33g5p2x  于2022-01-15 转载在 其他  
字(11.7k)|赞(0)|评价(0)|浏览(121)

本文整理了Java中java.util.ArrayList.subList()方法的一些代码示例,展示了ArrayList.subList()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ArrayList.subList()方法的具体详情如下:
包路径:java.util.ArrayList
类名称:ArrayList
方法名:subList

ArrayList.subList介绍

[英]Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations.

This method eliminates the need for explicit range operations (of the sort that commonly exist for arrays). Any operation that expects a list can be used as a range operation by passing a subList view instead of a whole list. For example, the following idiom removes a range of elements from a list:

list.subList(from, to).clear();

Similar idioms may be constructed for #indexOf(Object) and #lastIndexOf(Object), and all of the algorithms in the Collections class can be applied to a subList.

The semantics of the list returned by this method become undefined if the backing list (i.e., this list) is structurally modified in any way other than via the returned list. (Structural modifications are those that change the size of this list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.)
[中]返回此列表中指定的fromIndex(包含)和toIndex(独占)之间部分的视图。(如果fromIndex和toIndex相等,则返回的列表为空。)返回的列表由该列表支持,因此返回列表中的非结构性更改将反映在此列表中,反之亦然。返回的列表支持所有可选的列表操作。
此方法消除了显式范围操作的需要(通常存在于数组中)。通过传递子列表视图而不是整个列表,任何需要列表的操作都可以用作范围操作。例如,以下习惯用法从列表中删除一系列元素:

list.subList(from, to).clear();

对于#indexOf(Object)和#lastIndexOf(Object),可以构造类似的习惯用法,并且集合类中的所有算法都可以应用于子列表。
如果支持列表(即,此列表)以任何方式(而不是通过返回的列表)进行结构修改,则此方法返回的列表的语义将变得未定义。(结构修改是指更改此列表的大小,或以其他方式干扰列表,使正在进行的迭代可能产生不正确的结果。)

代码示例

代码示例来源:origin: stanfordnlp/CoreNLP

private static ArrayList<Word> cutLast(ArrayList<Word> s) {
 return new ArrayList<>(s.subList(0, s.size() - 1));
}

代码示例来源:origin: airbnb/epoxy

@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
 if (itemCount == 0) {
  // no-op
  return;
 }
 List<ModelState> modelsToRemove =
   currentStateList.subList(positionStart, positionStart + itemCount);
 for (ModelState model : modelsToRemove) {
  currentStateMap.remove(model.id);
 }
 modelsToRemove.clear();
 // Update positions of affected items
 int size = currentStateList.size();
 for (int i = positionStart; i < size; i++) {
  currentStateList.get(i).position -= itemCount;
 }
}

代码示例来源:origin: lealone/Lealone

public synchronized List<QueryEntry> getQueries() {
  // return a copy of the map so we don't have to
  // worry about external synchronization
  ArrayList<QueryEntry> list = new ArrayList<QueryEntry>();
  list.addAll(map.values());
  // only return the newest 100 entries
  Collections.sort(list, QUERY_ENTRY_COMPARATOR);
  return list.subList(0, Math.min(list.size(), maxQueryEntries));
}

代码示例来源:origin: cmusphinx/sphinx4

/**
 * Copies a path
 */
private static void duplicatePath(int lastPathIndex, State fromState,
    State toState, ArrayList<ArrayList<State>> paths) {
  ArrayList<State> lastPath = paths.get(lastPathIndex);
  // copy the last path to a new one, from start to current state
  int fromIndex = lastPath.indexOf(fromState);
  int toIndex = lastPath.indexOf(toState);
  if (toIndex == -1) {
    toIndex = lastPath.size() - 1;
  }
  ArrayList<State> newPath = new ArrayList<State>(lastPath.subList(
      fromIndex, toIndex));
  paths.add(newPath);
}

代码示例来源:origin: killme2008/Metamorphosis

if (!matchLimited || matchList.size() < limit - 1) {
    final String match = input.subSequence(index, m.start()).toString();
    matchList.add(match);
    index = m.end();
  else if (matchList.size() == limit - 1) { // last one
    final String match = input.subSequence(index, input.length()).toString();
    matchList.add(match);
    index = m.end();
if (!matchLimited || matchList.size() < limit) {
  matchList.add(input.subSequence(index, input.length()).toString());
return matchList.subList(0, resultSize).toArray(result);

代码示例来源:origin: google/guava

/**
 * For a given Enum type, creates an immutable map from each of the Enum's values to a
 * corresponding LockGraphNode, with the {@code allowedPriorLocks} and {@code
 * disallowedPriorLocks} prepopulated with nodes according to the natural ordering of the
 * associated Enum values.
 */
@VisibleForTesting
static <E extends Enum<E>> Map<E, LockGraphNode> createNodes(Class<E> clazz) {
 EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz);
 E[] keys = clazz.getEnumConstants();
 final int numKeys = keys.length;
 ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys);
 // Create a LockGraphNode for each enum value.
 for (E key : keys) {
  LockGraphNode node = new LockGraphNode(getLockName(key));
  nodes.add(node);
  map.put(key, node);
 }
 // Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
 for (int i = 1; i < numKeys; i++) {
  nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i));
 }
 // Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
 for (int i = 0; i < numKeys - 1; i++) {
  nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
 }
 return Collections.unmodifiableMap(map);
}

代码示例来源:origin: lisawray/groupie

@Override
public void add(int position, @NonNull Group group) {
  super.add(position, group);
  children.add(position, group);
  final int notifyPosition = getHeaderItemCount() + getItemCount(children.subList(0, position));
  notifyItemRangeInserted(notifyPosition, group.getItemCount());
  refreshEmptyState();
}

代码示例来源:origin: DataSketches/sketches-core

mem.putDouble(offset, weights_.get(i));
offset += Double.BYTES;
markBytes = MARK_SERDE.serializeToByteArray(marks_.subList(0, h_).toArray(new Boolean[0]));
mem.putByteArray(offset, markBytes, 0, markBytes.length);
offset += markBytes.length;

代码示例来源:origin: stackoverflow.com

if (!matchLimited || matchList.size() < limit - 1) {
    String match = input.subSequence(index, m.start()).toString();
    matchList.add(match);
    index = m.end();
  } else if (matchList.size() == limit - 1) { // last one
    String match = input.subSequence(index,
                     input.length()).toString();
    matchList.add(match);
    index = m.end();
if (!matchLimited || matchList.size() < limit)
  matchList.add(input.subSequence(index, input.length()).toString());
int resultSize = matchList.size();
if (limit == 0)
  while (resultSize > 0 && matchList.get(resultSize-1).equals(""))
    resultSize--;
String[] result = new String[resultSize];
return matchList.subList(0, resultSize).toArray(result);

代码示例来源:origin: apache/geode

public static void exportDiskStore(ArrayList<String> args, String outputDir) {
 File out = outputDir == null ? new File(".") : new File(outputDir);
 if (!out.exists()) {
  out.mkdirs();
 }
 String dsName = args.get(0);
 File[] dirs = argsToFile(args.subList(1, args.size()));
 try {
  DiskStoreImpl.exportOfflineSnapshot(dsName, dirs, out);
 } catch (Exception ex) {
  throw new GemFireIOException(" disk-store=" + dsName + ": " + ex, ex);
 }
}

代码示例来源:origin: stackoverflow.com

public static <T> ArrayList<T[]> chunks(ArrayList<T> bigList,int n){
  ArrayList<T[]> chunks = new ArrayList<T[]>();

  for (int i = 0; i < bigList.size(); i += n) {
    T[] chunk = (T[])bigList.subList(i, Math.min(bigList.size(), i + n)).toArray();         
    chunks.add(chunk);
  }

  return chunks;
}

代码示例来源:origin: google/j2objc

/**
 * For a given Enum type, creates an immutable map from each of the Enum's values to a
 * corresponding LockGraphNode, with the {@code allowedPriorLocks} and {@code
 * disallowedPriorLocks} prepopulated with nodes according to the natural ordering of the
 * associated Enum values.
 */
@VisibleForTesting
static <E extends Enum<E>> Map<E, LockGraphNode> createNodes(Class<E> clazz) {
 EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz);
 E[] keys = clazz.getEnumConstants();
 final int numKeys = keys.length;
 ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys);
 // Create a LockGraphNode for each enum value.
 for (E key : keys) {
  LockGraphNode node = new LockGraphNode(getLockName(key));
  nodes.add(node);
  map.put(key, node);
 }
 // Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
 for (int i = 1; i < numKeys; i++) {
  nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i));
 }
 // Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
 for (int i = 0; i < numKeys - 1; i++) {
  nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
 }
 return Collections.unmodifiableMap(map);
}

代码示例来源:origin: apache/hbase

public void removeComponents(int startIndex) {
 List<List<HStoreFile>> subList = components.subList(startIndex, components.size());
 for (List<HStoreFile> entry : subList) {
  size -= entry.size();
 }
 assert size >= 0;
 subList.clear();
}

代码示例来源:origin: naman14/Timber

public static List<Song> searchSongs(Context context, String searchString, int limit) {
  ArrayList<Song> result = getSongsForCursor(makeSongCursor(context, "title LIKE ?", new String[]{searchString + "%"}));
  if (result.size() < limit) {
    result.addAll(getSongsForCursor(makeSongCursor(context, "title LIKE ?", new String[]{"%_" + searchString + "%"})));
  }
  return result.size() < limit ? result : result.subList(0, limit);
}

代码示例来源:origin: apache/hive

/**
 * ExpressionTypes.
 *
 */
public static enum ExpressionTypes {
 FIELD, JEXL
};
public static final String LLAP_OUTPUT_FORMAT_KEY = "Llap";

代码示例来源:origin: apache/geode

public static void showDiskStoreMetadata(ArrayList<String> args) {
 String dsName = args.get(0);
 File[] dirs = argsToFile(args.subList(1, args.size()));
 try {
  DiskStoreImpl.dumpMetadata(dsName, dirs, showBuckets);
 } catch (Exception ex) {
  throw new GemFireIOException(" disk-store=" + dsName + ": " + ex, ex);
 }
}

代码示例来源:origin: chrisk44/Hijacker

void addToView(){
  int index;
  if(this.device instanceof AP){
    index = i;
    if(i>0 && getComparatorForAP()!=null){
      index = findIndex(tiles.subList(0, i), this, getComparatorForAP());
    }
    i++;
  }else{
    index = tiles.size();
    if(tiles.size() - i > 0 && getComparatorForST()!=null){
      index = findIndex(tiles.subList(i, tiles.size()), this, getComparatorForST()) + i;
    }
  }
  tiles.add(index, this);
  adapter.insert(this, index);
  onCountsChanged();
}
static int findIndex(List<Tile> list, Tile tile, Comparator<Tile> comp){

代码示例来源:origin: prestodb/presto

/**
 * For a given Enum type, creates an immutable map from each of the Enum's values to a
 * corresponding LockGraphNode, with the {@code allowedPriorLocks} and {@code
 * disallowedPriorLocks} prepopulated with nodes according to the natural ordering of the
 * associated Enum values.
 */
@VisibleForTesting
static <E extends Enum<E>> Map<E, LockGraphNode> createNodes(Class<E> clazz) {
 EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz);
 E[] keys = clazz.getEnumConstants();
 final int numKeys = keys.length;
 ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys);
 // Create a LockGraphNode for each enum value.
 for (E key : keys) {
  LockGraphNode node = new LockGraphNode(getLockName(key));
  nodes.add(node);
  map.put(key, node);
 }
 // Pre-populate all allowedPriorLocks with nodes of smaller ordinal.
 for (int i = 1; i < numKeys; i++) {
  nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i));
 }
 // Pre-populate all disallowedPriorLocks with nodes of larger ordinal.
 for (int i = 0; i < numKeys - 1; i++) {
  nodes.get(i).checkAcquiredLocks(Policies.DISABLED, nodes.subList(i + 1, numKeys));
 }
 return Collections.unmodifiableMap(map);
}

代码示例来源:origin: com.h2database/h2

public synchronized List<QueryEntry> getQueries() {
  // return a copy of the map so we don't have to
  // worry about external synchronization
  ArrayList<QueryEntry> list = new ArrayList<>(map.values());
  // only return the newest 100 entries
  Collections.sort(list, QUERY_ENTRY_COMPARATOR);
  return list.subList(0, Math.min(list.size(), maxQueryEntries));
}

代码示例来源:origin: bonnyfone/vectalign

ArrayList<PathParser.PathDataNode> transformTo = PathNodeUtils.transform(to, 0, true);
int fromSize = transformFrom.size();
int toSize = transformTo.size();
int min = Math.min(fromSize, toSize);
int numberOfSubAligns = (int) Math.max(1, min/2);
  startToIndex = i * toChunkSize;
  System.out.println("Subaligning FROM("+startFromIndex +","+endFromIndex+") - TO("+startToIndex +","+endToIndex+")");
  ArrayList<PathParser.PathDataNode>[] subAlign = doRawAlign(transformFrom.subList(startFromIndex, endFromIndex).toArray(new PathParser.PathDataNode[1]), transformTo.subList(startToIndex, endToIndex).toArray(new PathParser.PathDataNode[1]));
  finalFrom.addAll(subAlign[0]);
  finalTo.addAll(subAlign[1]);

相关文章

微信公众号

最新文章

更多