1 22 23 24 package com.mchange.v1.util; 25 26 import java.util.*; 27 import java.lang.reflect.Array ; 28 29 public final class IteratorUtils 30 { 31 public final static Iterator EMPTY_ITERATOR = new Iterator() 32 { 33 public boolean hasNext() 34 { return false; } 35 36 public Object next() 37 { throw new NoSuchElementException(); } 38 39 public void remove() 40 { throw new IllegalStateException (); } 41 }; 42 43 public static Iterator oneElementUnmodifiableIterator(final Object elem) 44 { 45 return new Iterator() 46 { 47 boolean shot = false; 48 49 public boolean hasNext() { return (!shot); } 50 51 public Object next() 52 { 53 if (shot) 54 throw new NoSuchElementException(); 55 else 56 { 57 shot = true; 58 return elem; 59 } 60 } 61 62 public void remove() 63 { throw new UnsupportedOperationException ("remove() not supported."); } 64 }; 65 } 66 67 public static boolean equivalent(Iterator ii, Iterator jj) 68 { 69 while (true) 70 { 71 boolean ii_hasnext = ii.hasNext(); 72 boolean jj_hasnext = jj.hasNext(); 73 if (ii_hasnext ^ jj_hasnext) 74 return false; 75 else if (ii_hasnext) 76 { 77 Object iiNext = ii.next(); 78 Object jjNext = jj.next(); 79 if (iiNext == jjNext) 80 continue; 81 else if (iiNext == null) 82 return false; 83 else if (!iiNext.equals(jjNext)) 84 return false; 85 } 86 else return true; 87 } 88 } 89 90 public static ArrayList toArrayList(Iterator ii, int initial_capacity) 91 { 92 ArrayList out = new ArrayList(initial_capacity); 93 while (ii.hasNext()) 94 out.add(ii.next()); 95 return out; 96 } 97 98 109 public static void fillArray(Iterator ii, Object [] fillMe, boolean null_terminate) 110 { 111 int i = 0; 112 int len = fillMe.length; 113 while ( i < len && ii.hasNext() ) 114 fillMe[ i++ ] = ii.next(); 115 if (null_terminate && i < len) 116 fillMe[i] = null; 117 } 118 119 public static void fillArray(Iterator ii, Object [] fillMe) 120 { fillArray( ii, fillMe, false); } 121 122 126 public static Object [] toArray(Iterator ii, int array_size, Class componentClass, boolean null_terminate) 127 { 128 Object [] out = (Object []) Array.newInstance( componentClass, array_size ); 129 fillArray(ii, out, null_terminate); 130 return out; 131 } 132 133 public static Object [] toArray(Iterator ii, int array_size, Class componentClass) 134 { return toArray( ii, array_size, componentClass, false ); } 135 136 141 public static Object [] toArray(Iterator ii, int ii_size, Object [] maybeFillMe) 142 { 143 if (maybeFillMe.length >= ii_size) 144 { 145 fillArray( ii, maybeFillMe, true ); 146 return maybeFillMe; 147 } 148 else 149 { 150 Class componentType = maybeFillMe.getClass().getComponentType(); 151 return toArray( ii, ii_size, componentType ); 152 } 153 } 154 155 private IteratorUtils() 156 {} 157 } 158 159 160 | Popular Tags |