/**
* 截取list,保留前l位
* Examples:
* list = [0, 1, 2, 3, 4, 5]
* subList(list, 3);
* list = [0, 1, 2]
*
* @param list 待截取list
* @param newLength 保留前length位數
* @param <T>
*/
public static <T> void subList(List<T> list, int newLength) {
if (null == list || newLength < 0 || newLength > list.size()) {
return;
}
for (int i = list.size() - 1; i >= newLength; i--) {
T t = list.remove(i);//避免List<Integer>的元素和index混淆,用返回值來指定API方法
}
}
/**
* Get a List that is a subList of this List. The
* subList begins at the specified {@code beginIndex} and
* extends to the element at index {@code endIndex - 1}.
* Thus the length of the subList is {@code endIndex-beginIndex}.
* <p>
* Examples:
* list = [0, 1, 2, 3, 4, 5]
* subList(list, 0 , 3);
* list = [0, 1, 2]
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @exception IndexOutOfBoundsException if the
* {@code beginIndex} is negative, or
* {@code endIndex} is larger than the length of
* this {@code list} object, or
* {@code beginIndex} is larger than
* {@code endIndex}.
*/
public static <T> void subList(List<T> list, int beginIndex, int endIndex) {
if (list == null || list.size() == 0) return;
if (beginIndex < 0) {
throw new ArrayIndexOutOfBoundsException(beginIndex);
}
int size = list.size();
if (endIndex > size) {
throw new ArrayIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new ArrayIndexOutOfBoundsException(subLen);
}
for (int i = size - 1; i >= 0; i--) {
if (i >= endIndex || i < beginIndex) {
T t = list.remove(i);
}
}
}
List截取
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.