1 33 package net.sf.jga.util; 34 35 import java.util.Iterator ; 36 import java.util.ListIterator ; 37 import java.util.NoSuchElementException ; 38 39 45 46 public class ArrayUtils { 47 48 static public String toString(Object [] arr) { 50 StringBuffer buf = new StringBuffer (); 51 buf.append("["); 52 for (int i = 0; i < arr.length; ++i) { 53 if (i > 0) 54 buf.append(','); 55 56 buf.append(arr[i]); 57 } 58 59 buf.append("]"); 60 return buf.toString(); 61 } 62 63 64 67 static public <E> ArrayIterator<E> iterate(E[] arr) { 68 return new ArrayIterator<E>(arr); 69 } 70 71 72 75 static public <T> Iterable <T> iterable(T[] ts) { 76 return new ArrayIterable<T>(ts); 77 } 78 79 80 83 static public class ArrayIterable<T> implements Iterable <T> { 84 85 private T[] _delegate; 87 88 public ArrayIterable(T[] ts) { _delegate = ts; } 89 90 94 public Iterator <T> iterator() { 95 if (_delegate == null) 96 return new EmptyIterator<T>(); 97 else 98 return new ArrayIterator<T>(_delegate); 99 } 100 } 101 102 105 static public class ArrayIterator<T> implements ListIterator <T> { 106 107 private T[] _array; 109 110 private int _idx; 112 113 private Boolean _goingForward; 116 117 120 public ArrayIterator(T[] array) { _array = array; } 121 122 126 public boolean hasNext() { return _idx < _array.length; } 127 128 public boolean hasPrevious() { return _idx > 0; } 129 130 public int nextIndex() { return _idx; } 131 132 public int previousIndex() { return _idx - 1; } 133 134 public T next() { 135 if (_idx >= _array.length ) 136 throw new NoSuchElementException (); 137 138 _goingForward = Boolean.TRUE; 139 return _array[_idx++]; 140 } 141 142 public T previous() { 143 if (_idx <= 0) 144 throw new NoSuchElementException (); 145 146 _goingForward = Boolean.FALSE; 147 return _array[--_idx]; 148 } 149 150 public void set(T value) { 151 if (_goingForward == null) 152 throw new IllegalStateException (); 153 154 if (_goingForward.booleanValue()) _array[_idx - 1] = value; 156 else 157 _array[_idx] = value; 158 } 159 160 public void add(T value) { 162 _goingForward = null; 163 throw new UnsupportedOperationException (); 164 } 165 166 public void remove() { 167 _goingForward = null; 168 throw new UnsupportedOperationException (); 169 } 170 } 171 } 172 | Popular Tags |