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));
52 return new String(buffer);
56 * sets the given value to kgram element at given index.
60 @SuppressWarnings("unchecked")
61 public void set(int index, T value){
62 if(index < 0 || index >= maxLength){
63 throw new ArrayIndexOutOfBoundsException(
64 "expected 0-" + (maxLength - 1) + ": " + index
68 throw new NullPointerException("null value");
71 values = (T[])Array.newInstance(value.getClass(), getKValue());
73 values[index] = value;
77 * returns an object of given index.
79 public T get(int index){
81 if(index < 0 || index >= maxLength){
82 throw new ArrayIndexOutOfBoundsException(
83 "expected 0-" + (maxLength - 1) + ": " + index
87 returnValue = values[index];
94 * adds value at last index.
96 * this object is called with given 2 when following situation,
98 * <li>{ 1, 3, null, null } -> { 1, 2, 3, null } and return 2<li>
99 * <li>{ 1, null, 3, null } -> { 1, 2, 3, null } and return 1<li>
100 * <li>{ 1, 2, 3, 4 } -> { 1, 2, 3, 4 } and return -1<li>
103 * @param value value for addition.
104 * @return added index.
106 public int add(T value){
108 for(int i = 0; i < values.length; i++){
109 if(values[i] == null){
119 * returns an array of elements this object has.
122 @SuppressWarnings("unchecked")
123 public T[] toArray(){
125 throw new IllegalStateException("this object has no elements.");
127 T[] newarray = (T[])Array.newInstance(
128 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);