001: /*
002: * Created on 25-Oct-2003
003: */
004: package uk.org.ponder.arrayutil;
005:
006: import java.util.ArrayList;
007: import java.util.Enumeration;
008: import java.util.List;
009:
010: import uk.org.ponder.util.AssertionException;
011:
012: /**
013: * Contains useful utility methods for operating on java.util.List instances.
014: * @author Bosmon
015: *
016: * The class
017: */
018: public class ListUtil {
019: public static final List EMPTY_LIST = new ArrayList(0);
020:
021: public static Enumeration getEnumeration(final List list) {
022: return new Enumeration() {
023: int pos = 0;
024:
025: public boolean hasMoreElements() {
026: return pos < list.size();
027: }
028:
029: public Object nextElement() {
030: return list.get(pos++);
031: }
032: };
033: }
034:
035: /** Construct a new List instance comprised of the single supplied entry **/
036:
037: public static List instance(Object entry) {
038: List togo = new ArrayList();
039: togo.add(entry);
040: return togo;
041: }
042:
043: /** Construct a new List instance filled with the supplied array of objects **/
044: public static List instance(Object[] init) {
045: List togo = new ArrayList();
046: append(togo, init);
047: return togo;
048: }
049:
050: /** Append the elements in the supplied array to the end of the supplied list **/
051: public static void append(List list, Object[] toappend) {
052: if (toappend != null) {
053: for (int i = 0; i < toappend.length; ++i) {
054: list.add(toappend[i]);
055: }
056: }
057: }
058:
059: public static void setSafe(List list, int index, Object toset) {
060: if (index >= list.size()) {
061: expandSize(list, index + 1);
062: }
063: list.set(index, toset);
064: }
065:
066: public static Object getSafe(List list, int index) {
067: if (index >= list.size()) {
068: expandSize(list, index + 1);
069: }
070: return list.get(index);
071: }
072:
073: public static void expandSize(List list, int newsize) {
074: for (int i = list.size(); i < newsize; ++i) {
075: list.add(null);
076: }
077: }
078:
079: public static void restrictSize(List list, int newsize) {
080: for (int i = list.size() - 1; i >= newsize; --i) {
081: list.remove(i);
082: }
083: }
084:
085: public static void setSize(List list, int newsize) {
086: if (newsize > list.size()) {
087: expandSize(list, newsize);
088: } else if (newsize < list.size()) {
089: restrictSize(list, newsize);
090: }
091: }
092:
093: public static Object pop(List list) {
094: int size = list.size();
095: if (size == 0) {
096: throw new AssertionException(
097: "Attempt to pop from empty stack");
098: } else {
099: Object togo = list.get(size - 1);
100: list.remove(size - 1);
101: return togo;
102: }
103: }
104:
105: public static Object peek(List list) {
106: return list.size() == 0 ? null : list.get(list.size() - 1);
107: }
108: }
|