1 package jp.sourceforge.stigmata.birthmarks.kgram;
3 import java.io.Serializable;
4 import java.lang.reflect.Array;
5 import java.util.Arrays;
8 * This class represents k-gram of the some sequence.
10 * @author Haruaki TAMADA
12 public class KGram<T> implements Serializable{
13 private static final long serialVersionUID = 273465874532523L;
14 // private List<T> list = new ArrayList<T>();
15 private int maxLength = 4;
20 * @param kvalue the number of elements of this object.
22 public KGram(int kvalue){
28 * @param kvalue the number of elements of this object.
30 public void setKValue(int kvalue){
31 this.maxLength = kvalue;
35 * returns k-value which is the number of elements.
36 * @return the number of elements.
38 public int getKValue(){
43 * returns string representation of this object.
46 public String toString(){
47 StringBuffer buffer = new StringBuffer("{ ");
48 for(int i = 0; i < maxLength; i++){
49 if(i != 0) buffer.append(", ");
50 buffer.append(get(i));
53 return new String(buffer);
57 * sets the given value to kgram element at given index.
61 @SuppressWarnings("unchecked")
62 public void set(int index, T value){
63 if(index < 0 || index >= maxLength){
64 throw new ArrayIndexOutOfBoundsException("expected 0-" + (maxLength - 1) + ": " + index);
67 throw new NullPointerException("null value");
70 values = (T[])Array.newInstance(value.getClass(), getKValue());
72 values[index] = value;
76 * returns an object of given index.
78 public T get(int index){
80 if(index < 0 || index >= maxLength){
81 throw new ArrayIndexOutOfBoundsException("expected 0-" + (maxLength - 1) + ": " + index);
84 returnValue = values[index];
91 * adds value at last index.
93 * this object is called with given 2 when following situation,
95 * <li>``{ 1, 3, null, null }'' -> ``{ 1, 2, 3, null }'' and return 2<li>
96 * <li>``{ 1, null, 3, null }'' -> ``{ 1, 2, 3, null }'' and return 1<li>
97 * <li>``{ 1, 2, 3, 4 }'' -> ``{ 1, 2, 3, 4 }'' and return -1<li>
100 * @param value value for addition.
101 * @return added index.
103 public int add(T value){
105 for(int i = 0; i < values.length; i++){
106 if(values[i] == null){
116 * returns an array of elements this object has.
119 @SuppressWarnings("unchecked")
120 public T[] toArray(){
122 throw new IllegalStateException("this object has no elements.");
124 T[] newarray = (T[])Array.newInstance(values[0].getClass(), getKValue());
125 System.arraycopy(values, 0, newarray, 0, getKValue());
130 public boolean equals(Object o){
131 if(o instanceof KGram){
132 KGram<?> kgram = (KGram<?>)o;
133 boolean flag = getKValue() == kgram.getKValue();
134 for(int i = 0; !flag && i < maxLength; i++){
135 if(!get(i).equals(kgram.get(i))){
146 public int hashCode(){
147 return Arrays.hashCode(values);