001/* 002 * $Id: Coefficients.java 4043 2012-07-25 16:46:06Z kredel $ 003 */ 004 005package edu.jas.ps; 006 007 008import java.io.Serializable; 009import java.util.HashMap; 010 011import edu.jas.structure.RingElem; 012 013 014/** 015 * Abstract class for generating functions for coefficients of power series. Was 016 * an interface, now this class handles the caching itself. 017 * @param <C> ring element type 018 * @author Heinz Kredel 019 */ 020 021public abstract class Coefficients<C extends RingElem<C>> implements Serializable { 022 023 024 /** 025 * Cache for already computed coefficients. 026 */ 027 public final HashMap<Integer, C> coeffCache; 028 029 030 /** 031 * Public no arguments constructor. 032 */ 033 public Coefficients() { 034 this(new HashMap<Integer, C>()); 035 } 036 037 038 /** 039 * Public constructor with pre-filled cache. 040 * @param cache pre-filled coefficient cache. 041 */ 042 public Coefficients(HashMap<Integer, C> cache) { 043 coeffCache = cache; 044 } 045 046 047 /** 048 * Get cached coefficient or generate coefficient. 049 * @param index of requested coefficient. 050 * @return coefficient at index. 051 */ 052 public C get(int index) { 053 if (coeffCache == null) { 054 return generate(index); 055 } 056 Integer i = index; 057 C c = coeffCache.get(i); 058 if (c != null) { 059 return c; 060 } 061 c = generate(index); 062 coeffCache.put(i, c); 063 return c; 064 } 065 066 067 /** 068 * Generate coefficient. 069 * @param index of requested coefficient. 070 * @return coefficient at index. 071 */ 072 protected abstract C generate(int index); 073 074}