public String getExitDesc() {
String str = "";
if(northRoom != null) {str += "north ";}
if(eastRoom != null) {str += "east ";}
if(southRoom != null) {str += "south ";}
if(westRoom != null) {str += "west ";}
return str;
}
上面这种方法直接定义一个String str去+=是一个不好的方法,因为每一次 += ,都会产生一个新的字符串对象,所以对系统的开销比较大。建议用StringBuffer以及它的append方法。如下:
public String getExitDesc() {
StringBuffer sb = new StringBuffer();
if(northRoom != null) {sb.appedn( "north ");}
if(eastRoom != null) {sb.append("east ");}
if(southRoom != null) {sb.append("south ");}
if(westRoom != null) {sb.append("west ");}
return sb.toString();
}
上面的StringBuffer对象 sb 每一次只在自己身上加字符串。