1 package jp.sourceforge.stigmata.birthmarks.kgram;
7 import java.io.Serializable;
8 import java.lang.reflect.Array;
9 import java.util.Arrays;
12 * This class represents k-gram of the some sequence.
14 * @author Haruaki TAMADA
17 public class KGram<T> implements Serializable{
18 private static final long serialVersionUID = 273465874532523L;
19 // private List<T> list = new ArrayList<T>();
20 private int maxLength = 4;
25 * @param kvalue the number of elements of this object.
27 public KGram(int kvalue){
33 * @param kvalue the number of elements of this object.
35 public void setKValue(int kvalue){
36 this.maxLength = kvalue;
40 * returns k-value which is the number of elements.
41 * @return the number of elements.
43 public int getKValue(){
48 * returns string representation of this object.
51 public String toString(){
52 StringBuffer buffer = new StringBuffer("{ ");
53 for(int i = 0; i < maxLength; i++){
54 if(i != 0) buffer.append(", ");
55 buffer.append(get(i));
58 return new String(buffer);
62 * sets the given value to kgram element at given index.
66 @SuppressWarnings("unchecked")
67 public void set(int index, T value){
68 if(index < 0 || index >= maxLength){
69 throw new ArrayIndexOutOfBoundsException("expected 0-" + (maxLength - 1) + ": " + index);
72 throw new NullPointerException("null value");
75 values = (T[])Array.newInstance(value.getClass(), getKValue());
77 values[index] = value;
81 * returns an object of given index.
83 public T get(int index){
85 if(index < 0 || index >= maxLength){
86 throw new ArrayIndexOutOfBoundsException("expected 0-" + (maxLength - 1) + ": " + index);
89 returnValue = values[index];
96 * adds value at last index.
98 * this object is called with given 2 when following situation,
100 * <li>``{ 1, 3, null, null }'' -> ``{ 1, 2, 3, null }'' and return 2<li>
101 * <li>``{ 1, null, 3, null }'' -> ``{ 1, 2, 3, null }'' and return 1<li>
102 * <li>``{ 1, 2, 3, 4 }'' -> ``{ 1, 2, 3, 4 }'' and return -1<li>
105 * @param value value for addition.
106 * @return added index.
108 public int add(T value){
110 for(int i = 0; i < values.length; i++){
111 if(values[i] == null){
121 * returns an array of elements this object has.
124 @SuppressWarnings("unchecked")
125 public T[] toArray(){
127 throw new IllegalStateException("this object has no elements.");
129 T[] newarray = (T[])Array.newInstance(values[0].getClass(), getKValue());
130 System.arraycopy(values, 0, newarray, 0, getKValue());
135 public boolean equals(Object o){
136 if(o instanceof KGram){
137 KGram<?> kgram = (KGram<?>)o;
138 boolean flag = getKValue() == kgram.getKValue();
139 for(int i = 0; !flag && i < maxLength; i++){
140 if(!get(i).equals(kgram.get(i))){
151 public int hashCode(){
152 return Arrays.hashCode(values);