001/* Copyright (C) 2013 TU Dortmund 002 * This file is part of AutomataLib, http://www.automatalib.net/. 003 * 004 * AutomataLib is free software; you can redistribute it and/or 005 * modify it under the terms of the GNU Lesser General Public 006 * License version 3.0 as published by the Free Software Foundation. 007 * 008 * AutomataLib is distributed in the hope that it will be useful, 009 * but WITHOUT ANY WARRANTY; without even the implied warranty of 010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 011 * Lesser General Public License for more details. 012 * 013 * You should have received a copy of the GNU Lesser General Public 014 * License along with AutomataLib; if not, see 015 * http://www.gnu.de/documents/lgpl.en.html. 016 */ 017package net.automatalib.words.impl; 018 019import java.util.Arrays; 020 021 022public class EnumAlphabet<E extends Enum<E>> extends ArrayAlphabet<E> { 023 024 private static <E> E[] extractEnumValues(Class<E> enumClazz, boolean withNull) { 025 E[] enumValues = enumClazz.getEnumConstants(); 026 if(enumValues == null) 027 throw new IllegalArgumentException("Class " + enumClazz.getName() + " is not an enumeration class!"); 028 if(!withNull) 029 return enumValues; 030 return Arrays.copyOf(enumValues, enumValues.length + 1); 031 } 032 033 public EnumAlphabet(Class<E> enumClazz, boolean withNull) { 034 super(extractEnumValues(enumClazz, withNull)); 035 } 036 037 @Override 038 public int getSymbolIndex(E symbol) throws IllegalArgumentException { 039 if(symbol == null) { 040 int lastIdx = symbols.length - 1; 041 if(symbols[lastIdx] == null) 042 return lastIdx; 043 throw new IllegalArgumentException("No such symbol: null"); 044 } 045 return symbol.ordinal(); 046 } 047 048 /* (non-Javadoc) 049 * @see net.automatalib.words.abstractimpl.AbstractAlphabet#compare(java.lang.Object, java.lang.Object) 050 */ 051 @Override 052 public int compare(E o1, E o2) { 053 if(o1 == o2) 054 return 0; 055 if(o1 == null) 056 return 1; 057 if(o2 == null) 058 return -1; 059 return o1.compareTo(o2); 060 } 061 062}