2017
May
25

字串相加,String Concatenation

"str1 + str2" 实作两个字串相加: 用正常的方式 A + B 即可,不用特别使用 "stringBuilder().append()" 这个方式,原因是 Java2 编译器会自动帮你将

String s = s1 + s2

Compile 成下列这种 ↓

String s = (new StringBuffer()).append(s1).append(s2).toString();

可参考这篇文章


回传空字串,阵列,减少使用 null

如果 Function 常常回传 null ,会造成使用该 function 的程式,必需写 if/else 来滤掉 null case ,程式的可读性会变差 。

JSON

处理 JSON 格式最好使用 org.json。

pom.xml
  1. <dependency>
  2. <groupId>org.json</groupId>
  3. <artifactId>json</artifactId>
  4. <version>20090211</version>
  5. </dependency>
App.java
  1. import org.json.JSONObject;
  2. import org.json.JSONArray;
  3. public class App
  4. {
  5. public static void main( String[] args )
  6. {
  7. JSONObject j = new JSONObject();
  8. j.put("key1", "value1")
  9. .put("key2", "value2");
  10.  
  11. }
  12. }

回應 (Leave a comment)