Java tutorial
//package com.java2s; // Licensed under the Apache License, Version 2.0 (the "License"); import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.RandomAccess; public class Main { /** * Resizes the passed list to N entries. Will add the specified object if * the list is smaller than the desired size, discard trailing entries if * larger. This is primarily used to presize a list that will be accessed * by index, but it may also be used to truncate a list for display. * * @return The list, as a convenience for callers * * @throws UnsupportedOperationException if the list does not implement * <code>RandomAccess</code> and its list iterator does not * support the <code>remove()</code> operation */ public static <T> List<T> resize(List<T> list, int newSize, T obj) { if (list instanceof ArrayList) ((ArrayList<T>) list).ensureCapacity(newSize); if (list.size() < newSize) { for (int ii = list.size(); ii < newSize; ii++) list.add(obj); } else if (list.size() > newSize) { if (list instanceof RandomAccess) { for (int ii = list.size() - 1; ii >= newSize; ii--) list.remove(ii); } else { ListIterator<T> itx = list.listIterator(newSize); while (itx.hasNext()) { itx.next(); itx.remove(); } } } return list; } /** * Resizes the passed list to N entries. Will add nulls if the list is * smaller than the desired size, discard trailing entries if larger. * This is primarily used to presize a list that will be accessed by * index, but it may also be used to truncate a list for display. * * @return The list, as a convenience for callers * @throws UnsupportedOperationException if the list does not implement * <code>RandomAccess</code> and its list iterator does not * support the <code>remove()</code> operation */ public static <T> List<T> resize(List<T> list, int newSize) { return resize(list, newSize, null); } }