以前写代码的时候,没有考虑到效率的问题。if……else if……else if 写了老长。如果数据量特别大的话,其实会影响到程序的效率。因为,if语句是从上到下一个个判断的,直到条件为真才退出。而switch……case 则不是从上到下进行验证的,因此效率要比if else高。
可惜的是,switch case 不支持字符串,着实让我伤脑筋。今天在网上查了些资料,得到一些提示,拿出来晒晒。
if……else例子:
public void ifElse(){
String name=“haha”;
if(name.equals(“yes”))
{
System.out.println(“is yes”);
}
else if(name.equals(“hello”))
{
System.out.println(“is hello”);
}
else if(name.equals(“in”))
{
System.out.println(“is in”);
}
else if(name.equals(“haha”))
{
System.out.println(“is haha”);
}
}
代码难看,如果if 再长一点,就难受了。
用switch case 实现:
public void switchCaseStr() {
Map<String,Integer> map=new HashMap<String, Integer>();
map.put(“hello”, 1);
map.put(“haha”, 2);
map.put(“yes”, 3);
map.put(“in”, 4);
String str=“hello”;
switch(map.get(str))
{
case 3:
System.out.println(“yes”);
break;
case 1:
System.out.println(“hello”);
break;
case 2:
System.out.println(“haha”);
break;
case 4:
System.out.println(“in”);
break;
default:
System.out.println(“default”);
}
}
不仅从效率上有提高,而且代码也更好看。当然,switch case 还可以嵌套使用。
public void switchCaseStr(){
Map<String,Integer> map=new HashMap<String, Integer>();
map.put(“hello”, 1);
map.put(“haha”, 2);
map.put(“yes”, 3);
map.put(“in”, 4);
String str=“hello”;
switch(map.get(str))
{
case 3:
System.out.println(“yes”);
break;
case 1:
System.out.println(“hello”);
String st=“in”;
switch(map.get(st))
{
case 2:
System.out.println(“haha”);
break;
case 4:
System.out.println(“in”);
break;
}
break;
default:
System.out.println(“default”);
}
}
当然,也可以有其它的方法实现。本人喜欢用hashmap,效率应该比 List好一点吧,个人觉得。