KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jac > util > Enum


1 /*
2   Copyright (C) 2002 Renaud Pawlak <renaud@aopsys.com>
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU Lesser General Public License as
6   published by the Free Software Foundation; either version 2 of the
7   License, or (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12   GNU Lesser General Public License for more details.
13
14   You should have received a copy of the GNU Lesser General Public License
15   along with this program; if not, write to the Free Software
16   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */

17
18 package org.objectweb.jac.util;
19
20 import java.util.Arrays JavaDoc;
21 import java.util.List JavaDoc;
22
23 public class Enum {
24     String JavaDoc[] values;
25     int start = 0;
26     int step = 1;
27     public Enum(String JavaDoc[] values, int start, int step) {
28         this.values = values;
29         this.start = start;
30         this.step = step;
31     }
32
33     /**
34      * Converts an integer value to it's string representation
35      * @param index the integer value to convert
36      * @throws InvalidIndexException
37      */

38     public String JavaDoc int2string(int index) {
39         if (((float)(index-start)/((float)step))!=(float)((index-start)/step))
40             throw new InvalidIndexException(index);
41         String JavaDoc value;
42         try {
43             value=values[(index-start)/step];
44         } catch(Exception JavaDoc e) {
45             throw new InvalidIndexException(index);
46         }
47         return value;
48     }
49     /**
50      * Converts a string value to an integer. Throws an exception if
51      * the enum does not define that string.
52      */

53     public int string2int(String JavaDoc string) {
54         if (string==null)
55             throw new RuntimeException JavaDoc("Invalid string value null for enum");
56         int index = start;
57         for(int i=0; i<values.length; i++) {
58             if (string.equals(values[i])) {
59                 return index;
60             } else {
61                 index += step;
62             }
63         }
64         throw new RuntimeException JavaDoc("Invalid string value '"+string+"' for enum");
65     }
66     public List JavaDoc getValues() {
67         return Arrays.asList(values);
68     }
69     public int getStart() {
70         return start;
71     }
72     public int getStep() {
73         return step;
74     }
75 }
76
Popular Tags