001package es.ucm.fdi.gaia.jcolibri.method.retrieve.NNretrieval.similarity.local; 002 003 004import es.ucm.fdi.gaia.jcolibri.exception.NoApplicableSimilarityFunctionException; 005import es.ucm.fdi.gaia.jcolibri.method.retrieve.NNretrieval.similarity.LocalSimilarityFunction; 006 007/** 008 * This function returns the similarity of two enum values as the their distance 009 * sim(x,y)=|ord(x) - ord(y)| 010 * 011 * @author Juan A. Recio-Garc�a 012 */ 013public class EnumDistance implements LocalSimilarityFunction { 014 015 /** 016 * Applies the similarity function. 017 * 018 * @param o1 019 * StringEnum or String 020 * @param o2 021 * StringEnum or String 022 * @return the result of apply the similarity function. 023 */ 024 public double compute(Object o1, Object o2) throws NoApplicableSimilarityFunctionException { 025 if ((o1 == null) || (o2 == null)) 026 return 0; 027 if(!(o1 instanceof Enum)) 028 throw new NoApplicableSimilarityFunctionException(this.getClass(), o1.getClass()); 029 if(!(o2 instanceof Enum)) 030 throw new NoApplicableSimilarityFunctionException(this.getClass(), o2.getClass()); 031 032 Enum<?> e1 = (Enum<?>)o1; 033 Enum<?> e2 = (Enum<?>)o2; 034 035 double size = e1.getDeclaringClass().getEnumConstants().length; 036 double diff = Math.abs(e1.ordinal() - e2.ordinal()); 037 038 return 1 - (diff / size); 039 } 040 041 /** Applicable to Enum */ 042 public boolean isApplicable(Object o1, Object o2) 043 { 044 if((o1==null)&&(o2==null)) 045 return true; 046 else if(o1==null) 047 return o2 instanceof Enum; 048 else if(o2==null) 049 return o1 instanceof Enum; 050 else 051 return (o1 instanceof Enum)&&(o2 instanceof Enum); 052 } 053 054}