Strings problem
hi, i've got an issue. i have few strings(about 100):
publicstatic String EPWR ="EPWR";
publicstatic String LICDS ="LICDS";
publicstatic String LICD ="LICD";
.........
publicstatic String CPCU ="CPCU";
now i want put all this string into LinkedList, but i want to use loop and use those strings declared above. i want to do this fastest as possible. thanks for any advice, best regards, alcatraz
the best solution is get rid of all those constants, 100+ constitutes data not program constants (charsets excepted, of course)... So
Option 1. put the strings in a file, and slurp them into a list... and here's one I prepared earlier.public static List<String> readFileIntoList(String filename)
throws IOException, FileNotFoundException
{
BufferedReader in = null;
List<String> out = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader(filename));
String line = null;
while ( (line = in.readLine()) != null ) {
out.add(line);
}
} finally {
try {if(in!=null)in.close();}catch(Exception e){}
}
return out;
}
Option 2. read 'em from .properties file... there's tut's gallore on this, and I spotted a free "properties for dummies" wrapper classes the other day (@javaRanch I think), except I can't find it again, and I think I'd like a copy, It was really kinda cute.
Option 3. read 'em from an XML document... again there's all the tut's you could hope for including sun's here: http://java.sun.com/xml/tutorial_intro.html
Option 4. if you really must hard code them... create an array and use static <T> List<T> Arrays.asList(T... a) - Returns a fixed-size list backed by the specified array.
see: http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#asList(T...)
for exampleString[] tmp = { "EPWR", "LICDS", "LICD", "CPU", ..... };
List<String> strangeCodes = Arrays.asList(tmp );
Cheers. Keith.
Create an initialised string array, then you can transform it to a list easilly enough.
public final String[] strings {
"EPWR",
"LICDS",
... etc
};
public List<String> listOfStrings = new LinkedList<String>(Arrays.asList(strings);