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(
65 "expected 0-" + (maxLength - 1) + ": " + index
69 throw new NullPointerException("null value");
72 values = (T[])Array.newInstance(value.getClass(), getKValue());
74 values[index] = value;
78 * returns an object of given index.
80 public T get(int index){
82 if(index < 0 || index >= maxLength){
83 throw new ArrayIndexOutOfBoundsException(
84 "expected 0-" + (maxLength - 1) + ": " + index
88 returnValue = values[index];
95 * adds value at last index.
97 * this object is called with given 2 when following situation,
99 * <li>{ 1, 3, null, null } -> { 1, 2, 3, null } and return 2<li>
100 * <li>{ 1, null, 3, null } -> { 1, 2, 3, null } and return 1<li>
101 * <li>{ 1, 2, 3, 4 } -> { 1, 2, 3, 4 } and return -1<li>
104 * @param value value for addition.
105 * @return added index.
107 public int add(T value){
109 for(int i = 0; i < values.length; i++){
110 if(values[i] == null){
120 * returns an array of elements this object has.
123 @SuppressWarnings("unchecked")
124 public T[] toArray(){
126 throw new IllegalStateException("this object has no elements.");
128 T[] newarray = (T[])Array.newInstance(
129 values[0].getClass(), getKValue()
131 System.arraycopy(values, 0, newarray, 0, getKValue());
136 public boolean equals(Object o){
137 if(o instanceof KGram){
138 KGram<?> kgram = (KGram<?>)o;
139 boolean flag = getKValue() == kgram.getKValue();
140 for(int i = 0; !flag && i < maxLength; i++){
141 if(!get(i).equals(kgram.get(i))){
152 public int hashCode(){
153 return Arrays.hashCode(values);