1 33 package net.sf.jga.fn.algorithm; 34 35 import java.util.Collection ; 36 import java.util.Collections ; 37 import java.util.Vector ; 38 import net.sf.jga.fn.BinaryFunctor; 39 import net.sf.jga.fn.UnaryFunctor; 40 import net.sf.jga.fn.comparison.NotEqualTo; 41 import net.sf.jga.util.EmptyIterator; 42 import net.sf.jga.util.FindIterator; 43 import net.sf.jga.util.LookAheadIterator; 44 import java.util.Iterator ; 45 46 57 58 public class FindMismatch<T> extends LookAheadFunctor<T> { 59 60 static final long serialVersionUID = -5406536818520367561L; 61 62 private Collection <? extends T> _elements; 64 65 private BinaryFunctor<T,T,Boolean > _bf; 67 68 private LookAheadIterator<T> _elemIter; 70 71 private T _mismatch; 73 74 79 public FindMismatch(Collection <? extends T> elements) { 80 this(elements, new NotEqualTo<T>()); 81 } 82 83 89 public FindMismatch(Collection <? extends T> elements, 90 BinaryFunctor<T,T,Boolean > neq) 91 { 92 _elements = (elements == null) ? new Vector <T>() : elements; 93 _bf = neq; 94 } 95 96 105 public FindMismatch(Iterator<? extends T> iter, 106 BinaryFunctor<T,T,Boolean > neq) 107 { 108 if (iter == null) 109 iter = new EmptyIterator<T>(); 110 111 _elemIter = new LookAheadIterator<T>(iter); 112 _bf = neq; 113 } 114 115 120 public Collection <? extends T> getElements() { 121 return (_elements == null) ? null : 122 Collections.unmodifiableCollection(_elements); 123 } 124 125 128 129 public BinaryFunctor<T,T,Boolean > getComparisonFn() { 130 return _bf; 131 } 132 133 140 141 144 public T getMismatchedElement() { 145 if (_elemIter == null) 146 throw new IllegalStateException (); 147 148 return _mismatch; 149 } 150 151 152 154 165 public LookAheadIterator<T> fn(Iterator<? extends T> iterator) { 166 if (_elemIter == null) 167 _elemIter = new LookAheadIterator<T>(_elements.iterator()); 168 169 LookAheadIterator<T> lai = wrap(iterator, 1); 170 while (lai.hasNextPlus(1) && _elemIter.hasNextPlus(1)) { 171 T arg1 = lai.peek(1); 172 T arg2 = _elemIter.peek(1); 173 if (_bf.fn(arg1,arg2)) { 174 _mismatch = _elemIter.next(); 175 return lai; 176 } 177 lai.next(); 178 _elemIter.next(); 179 } 180 181 return lai; 182 } 183 184 188 public void accept(net.sf.jga.fn.Visitor v) { 189 if (v instanceof FindMismatch.Visitor) 190 ((FindMismatch.Visitor)v).visit(this); 191 else 192 v.visit(this); 193 } 194 195 197 public String toString() { 198 return "FindMismatch"; 199 } 200 201 203 207 public interface Visitor extends net.sf.jga.fn.Visitor { 208 public void visit(FindMismatch host); 209 } 210 211 } 212 | Popular Tags |