在我正在制作的程序中,我试图获取给定季节的格式化季节名称(格式化后的格式。我将格式化的名称保留在界面中,因为如果要使用地图,则不必要重新生成,因为我没有创建TeamBuilder的实例
“季节”界面:
public interface Seasons {
/*
* Contains a formatted list of seasons.
*
* An interface is being used as an alternative to using a Map in the
* TeamBuilder class, since calling parseTeam would have to build
* mappings for the seasons each time it
* was called. This way, the formatted name can simply be grabbed
*/
final String Skyrise = "Skyrise";
final String Toss_Up = "Toss%20Up";
final String Sack_Attack = "Sack%20Attack";
final String GateWay = "Gateway";
final String Round_Up = "Round%20Up";
final String Clean_Sweep = "Clean%20Sweep";
final String Elevation = "Elevation";
final String Bridge_Battle = "Bridge%20Battle";
final String Nothing_But_Net = "Nothing%20But%20Net";
final String Starstruck = "Starstruck";
final String In_The_Zone = "In%20The%20Zone";
final String Turning_Point = "Turning%20Point";
}
当我尝试抓住这些季节时,问题就来了。我的TeamBuilder类接受一个无格式的参数(字符串季节)。 我的问题是,有什么方法可以使用String参数作为方法来从接口中获取特定项?这比使用HashMap更可取,因为HashMap会不必要地重新生成相同的内容信息
所有这些类都可以在该项目的Github页上找到。
答案 0 :(得分:3)
如果要以键入方式进行操作,可以为此使用Enum:
enum Season{
Skyrise,Toss_Up, Sack_Attack;
@Override
public String toString() {
switch(this){
case Skyrise: return "Skyrise";
case Toss_Up: return "Toss%20Up";
case Sack_Attack: return "Sack_Attack";
default: return "";
}
}
}
public class main{
public static void printSeason(Seasons seasons){
System.out.println(seasons);
}
public static void main(String[] args) {
Seasons e = Seasons.Skyrise;
printSeason(e);
System.out.println(e);
}
}
由于编译器在内部调用toString(),因此像我的示例一样,您可以将参数作为Seasons或String传递。
如果您仍想使用没有“不必要地重新生成”的地图,则可以将静态字段与静态初始值设定项一起使用,如下所示:
class Seasons {
private static Map<String,String> map = new HashMap<>();
static {
map.put("Skyrise", "Skyrise");
map.put("Toss_Up", "Toss%20Up");
}
public static String getFormatted(String key){
return map.getOrDefault(key,"");
}
}
class main{
public static void main(String[] args) {
System.out.println(Seasons.getFormatted("Skyrise"));
}
}
答案 1 :(得分:1)
只需整合到Snoob答案上,您就可以使用字段枚举,所以:
enum Season
{
Skyrise("Skyrise"),
Toss_Up("Toss%20Up"),
Sack_Attack("Sack%20Attack")
;
public final String fancyName;
private Season(String fancyName)
{
this.fancyName = fancyName;
}
}
您确实拥有所有好处,而没有任何缺点。