java中的char数组只不过是String
java中的a。您可以在 Java7 的 switch-case 中使用字符串,但我不知道比较的效率。
因为只有你 char 数组的最后一个元素似乎有意义,所以你可以用它做一个 switch case。就像是
private static final int VERSION_INDEX = 3;
...
char[] version = // get it somehow
switch (version[VERSION_INDEX]) {
case '5':
break;
// etc
}
...
编辑
更多面向对象的版本。
public interface Command {
void execute();
}
public class Version {
private final Integer versionRepresentation;
private Version (Integer versionRep) {
this.versionRepresentation = versionRep;
}
public static Version get(char[] version) {
return new Version(Integer.valueOf(new String(version, "US-ASCII")));
}
@Override
public int hashCode() {
return this.versionRepresentation.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Version) {
Version that = (Version) obj;
return that.versionRepresentation.equals(this.versionRepresentation);
}
return false;
}
}
public class VersionOrientedCommandSet {
private final Command EMPTY_COMMAND = new Command() { public void execute() {}};
private final Map<Version, Command> versionOrientedCommands;
private class VersionOrientedCommandSet() {
this.versionOrientedCommands = new HashMap<Version, Command>();
}
public void add(Version version, Command command) {
this.versionOrientedCommands.put(version, command);
}
public void execute(Version version) throw CommandNotFoundException {
Command command = this.versionOrientedCommands.get(version);
if (command != null) {
command.execute();
} else {
throw new CommandNotFoundException("No command registered for version " + version);
}
}
}
// register you commands to VersionOrientedCommandSet
char[] versionChar = // got it from somewhere
Version version = Version.get(versionChar);
versionOrientedCommandSet.execute(version);
大量的代码 呵呵 你会有一点热身成本,但如果你的程序被执行多次,你将获得地图的效率:P