Advertisement
crassus9999

Untitled

Apr 16th, 2014
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.47 KB | None | 0 0
  1. package cz.cvut.k36.pr2.hw.hw06.impl;
  2.  
  3. import cz.cvut.k36.pr2.hw.hw06.Function;
  4. import cz.cvut.k36.pr2.hw.hw06.Pr2List;
  5. import cz.cvut.k36.pr2.hw.hw06.Predicate;
  6. import java.util.NoSuchElementException;
  7.  
  8. /**
  9.  *
  10.  * @author Lukas
  11.  */
  12. public class FilterView<T> extends View<T> {
  13.    
  14.     Pr2List<T> source;
  15.     final Predicate<T> predicate;
  16.     Boolean isEmpty;
  17.  
  18.     public FilterView(Pr2List<T> source, Predicate<T> predicate) {
  19.         this.source = source;
  20.         this.predicate = predicate;
  21.     }
  22.  
  23.     @Override
  24.     public T head() {
  25.         if (isEmpty())
  26.             throw new NoSuchElementException("Prázdný list.");
  27.         return source.head();
  28.     }
  29.    
  30.     @Override
  31.     public Pr2List<T> tail() {
  32.         if (isEmpty())
  33.             throw new UnsupportedOperationException("Prázdný list.");
  34.         return new FilterView(source.tail(), predicate);
  35.     }
  36.    
  37.     @Override
  38.     public boolean isEmpty() {
  39.         if(isEmpty != null) return isEmpty;
  40.         if(source.isEmpty()) return isEmpty = true;
  41.        
  42.         if(predicate.apply(source.head())) return isEmpty = false;
  43.        
  44.         source = source.tail();
  45.         return isEmpty();
  46.     }
  47.    
  48.     @Override
  49.     public int size() {
  50.         if(source.isEmpty()) return 0;
  51.        
  52.         if(predicate.apply(source.head()))
  53.             return 1 + new FilterView(source.tail(), predicate).size();
  54.        
  55.         source = source.tail();
  56.         return size();
  57.     }
  58.    
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement