如何为arraylist返回指定的大小?

xe55xuns  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(260)

关闭。这个问题需要细节或清晰。它目前不接受答案。
**想改进这个问题吗?**通过编辑这个帖子来添加细节并澄清问题。

上个月关门了。
改进这个问题
我试图返回列表中特定数量的元素。我知道 size() 方法返回列表中元素的总数。但我只想从列表中返回3个元素。我该怎么做呢?

@Override
public int getItemCount() {
    return stockInformaiton.size();
}
zu0ti5jz

zu0ti5jz1#

您可以通过以下代码解决此问题:(如果列表至少包含3项,则仅显示3项,否则将显示0、1或2项。)

@Override
public int getItemCount() {
    int sz = stockInformaiton.size();
    if (sz < 3) {
        return sz;
    }
    return 3;
}
emeijp43

emeijp432#

使用java.util.list子列表

/**
 * Returns a view of the portion of this list between the specified
 * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.  (If
 * {@code fromIndex} and {@code 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 supported
 * by this list.<p>
 *
 * 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:
 * <pre>{@code
 *      list.subList(from, to).clear();
 * }</pre>
 * Similar idioms may be constructed for {@code indexOf} and
 * {@code lastIndexOf}, and all of the algorithms in the
 * {@code Collections} class can be applied to a subList.<p>
 *
 * The semantics of the list returned by this method become undefined if
 * the backing list (i.e., this list) is <i>structurally modified</i> 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.)
 *
 * @param fromIndex low endpoint (inclusive) of the subList
 * @param toIndex high endpoint (exclusive) of the subList
 * @return a view of the specified range within this list
 * @throws IndexOutOfBoundsException for an illegal endpoint index value
 *         ({@code fromIndex < 0 || toIndex > size ||
 *         fromIndex > toIndex})
 */
List<E> subList(int fromIndex, int toIndex);

相关问题