001 /* 002 * ArrayHistogram1D 003 * 004 * Copyright (c) 2001, 2002 Marco Schmidt <marcoschmidt@users.sourceforge.net> 005 * All rights reserved. 006 */ 007 008 package net.sourceforge.jiu.color.data; 009 010 import net.sourceforge.jiu.color.data.Histogram1D; 011 012 /** 013 * A one-dimensional histogram data class that stores its counters in memory. 014 * Counters are stored in an <code>int</code> array of length 015 * {@link #getMaxValue()}<code> + 1</code> so that <code>k</code> 016 * values will require <code>k * 4</code> bytes. 017 * @author Marco Schmidt 018 */ 019 public class ArrayHistogram1D implements Histogram1D 020 { 021 private int[] data; 022 023 /** 024 * Creates a histogram with the argument's number of values, from 025 * <code>0</code> to <code>numValues - 1</code>. 026 * 027 * @param numValues the number of counters in the histogram; must be one or larger 028 * @throws IllegalArgumentException if the argument is smaller than one 029 */ 030 public ArrayHistogram1D(int numValues) 031 { 032 if (numValues < 1) 033 { 034 throw new IllegalArgumentException("Must have at least one entry; numValues=" + numValues); 035 } 036 data = new int[numValues]; 037 } 038 039 public void clear() 040 { 041 // OPTIMIZE 042 // we could use java.util.Arrays.fill, but that would require Java 1.2+: 043 // Arrays.fill(data, 0); 044 for (int i = 0; i < data.length; i++) 045 { 046 data[i] = 0; 047 } 048 } 049 050 public int getEntry(int index) 051 { 052 try 053 { 054 return data[index]; 055 } 056 catch (ArrayIndexOutOfBoundsException aioobe) 057 { 058 throw new IllegalArgumentException("Not a valid index: " + index); 059 } 060 } 061 062 public int getMaxValue() 063 { 064 return data.length - 1; 065 } 066 067 public int getNumUsedEntries() 068 { 069 int result = 0; 070 for (int i = 0; i < data.length; i++) 071 { 072 if (data[i] > 0) 073 { 074 result++; 075 } 076 } 077 return result; 078 } 079 080 public void increaseEntry(int index) 081 { 082 try 083 { 084 data[index]++; 085 } 086 catch (ArrayIndexOutOfBoundsException aioobe) 087 { 088 throw new IllegalArgumentException("Not a valid index: " + index); 089 } 090 } 091 092 public void setEntry(int index, int newValue) 093 { 094 try 095 { 096 data[index] = newValue; 097 } 098 catch (ArrayIndexOutOfBoundsException aioobe) 099 { 100 throw new IllegalArgumentException("Not a valid index: " + index); 101 } 102 } 103 }