《阿里巴巴 Java 开发手册》是阿里巴巴集团技术团队的集体智慧结晶和经验总结, 经历了多次大规模一线实战的检验及不断的完善, 系统化地整理成册, 反馈给广大开发者. 现代软件行业的高速发展对开发者的综合素质要求越来越高, 因为不仅是编程知识点, 其它维度的知识点也会影响到软件的最终交付质量.
他凝聚了阿里集团很多同学的知识智慧和经验, 这些经验甚至是用血淋淋的故障换来的, 希望前车之鉴, 后车之师, 能够帮助更多的开发者少踩坑, 杜绝踩重复的坑.
手册中很多规约其实都有很多背后的思考的, 但是需要声明一点: 笔者并非手册的编写者, 也是一位使用者, 本场 Chat 将站在使用者的角度, 试图揣测一下手册中部分约定背后的思考.
- // 传统的字符串产生方式, 如果没有要记录 Debug 等级的信息, 就会浪费时间在产生不必要的信息上
- logger.debug("There are now" + count + "user accounts:" + userAccountList);
- // 为了避免上述问题, 我们可以先检查是不是开启了 Debug 信息记录功能, 只是程序的编码会比较复杂
- if (logger.isDebugEnabled()) {
- logger.debug("There are now" + count + "user accounts:" + userAccountList);
- }
- // 如果 Debug 等级没有开启, 则不会产生不必要的字符串, 同时也能保持程序编码的简洁
- logger.debug("There are now {} user accounts: {}", count, userAccountList);
- boolean success
- boolean isSuccess
- Boolean success
- Boolean isSuccess
- class Model1 {
- private Boolean isSuccess;
- public void setSuccess(Boolean success) {
- isSuccess = success;
- }
- public Boolean getSuccess() {
- return isSuccess;
- }
- }
- class Model2 {
- private Boolean success;
- public Boolean getSuccess() {
- return success;
- }
- public void setSuccess(Boolean success) {
- this.success = success;
- }
- }
- class Model3 {
- private boolean isSuccess;
- public boolean isSuccess() {
- return isSuccess;
- }
- public void setSuccess(boolean success) {
- isSuccess = success;
- }
- }
- class Model4 {
- private boolean success;
- public boolean isSuccess() {
- return success;
- }
- public void setSuccess(boolean success) {
- this.success = success;
- }
- }
- public <PropertyType> get<PropertyName>();
- public void set<PropertyName>(<PropertyType> a);
- public boolean is<PropertyName>();
- public void set<PropertyName>(boolean m);
- public class BooleanMainTest {
- public static void main(String[] args) throws IOException {
- // 定一个 Model3 类型
- Model3 model3 = new Model3();
- model3.setSuccess(true);
- // 使用 fastjson(1.2.16) 序列化 model3 成字符串并输出
- System.out.println("Serializable Result With fastjson :" + JSON.toJSONString(model3));
- // 使用 Gson(2.8.5) 序列化 model3 成字符串并输出
- Gson gson =new Gson();
- System.out.println("Serializable Result With Gson :" +gson.toJson(model3));
- // 使用 jackson(2.9.7) 序列化 model3 成字符串并输出
- ObjectMapper om = new ObjectMapper();
- System.out.println("Serializable Result With jackson :" +om.writeValueAsString(model3));
- }
- }
- class Model3 implements Serializable {
- private static final long serialVersionUID = 1836697963736227954L;
- private boolean isSuccess;
- public boolean isSuccess() {
- return isSuccess;
- }
- public void setSuccess(boolean success) {
- isSuccess = success;
- }
- public String getHollis(){
- return "hollischuang";
- }
- }
- Serializable Result With fastjson :{"hollis":"hollischuang","success":true}
- Serializable Result With Gson :{"isSuccess":true}
- Serializable Result With jackson :{"success":true,"hollis":"hollischuang"}
- Serializable Result With fastjson :{
- "success":true
- }
- Serializable Result With Gson :{
- "isSuccess":true
- }
- Serializable Result With jackson :{
- "success":true
- }
- public class BooleanMainTest {
- public static void main(String[] args) throws IOException {
- Model3 model3 = new Model3();
- model3.setSuccess(true);
- Gson gson =new Gson();
- System.out.println(gson.fromJson(JSON.toJSONString(model3),Model3.class));
- }
- }
- class Model3 implements Serializable {
- private static final long serialVersionUID = 1836697963736227954L;
- private boolean isSuccess;
- public boolean isSuccess() {
- return isSuccess;
- }
- public void setSuccess(boolean success) {
- isSuccess = success;
- }
- @Override
- public String toString() {
- return new StringJoiner(",", Model3.class.getSimpleName() + "[", "]")
- .add("isSuccess=" + isSuccess)
- .toString();
- }
- }
- boolean success
- Boolean success
- /**
- * @author Hollis
- */
- public class BooleanMainTest {
- public static void main(String[] args) {
- Model model1 = new Model();
- System.out.println("default model :" + model1);
- }
- }
- class Model {
- /**
- * 定一个 Boolean 类型的 success 成员变量
- */
- private Boolean success;
- /**
- * 定一个 boolean 类型的 failure 成员变量
- */
- private boolean failure;
- /**
- * 覆盖 toString 方法, 使用 Java 8 的 StringJoiner
- */
- @Override
- public String toString() {
- return new StringJoiner(",", Model.class.getSimpleName() + "[", "]")
- .add("success=" + success)
- .add("failure=" + failure)
- .toString();
- }
- }
- if (obj instanceof String) {
- writeString((String) obj, unshared);
- } else if (cl.isArray()) {
- writeArray(obj, desc, unshared);
- } else if (obj instanceof Enum) {
- writeEnum((Enum) obj, desc, unshared);
- } else if (obj instanceof Serializable) {
- writeOrdinaryObject(obj, desc, unshared);
- } else {
- if (extendedDebugInfo) {
- throw new NotSerializableException(
- cl.getName() + "\n" + debugInfoStack.toString());
- } else {
- throw new NotSerializableException(cl.getName());
- }
- }
- public class SerializableDemo1 {
- public static void main(String[] args) {
- //Initializes The Object
- User1 user = new User1();
- user.setName("hollis");
- //Write Obj to File
- ObjectOutputStream oos = null;
- try {
- oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
- oos.writeObject(user);
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- IOUtils.closeQuietly(oos);
- }
- }
- }
- class User1 implements Serializable {
- private static final long serialVersionUID = 1L;
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- class User1 implements Serializable {
- private static final long serialVersionUID = 2L;
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- public class SerializableDemo2 {
- public static void main(String[] args) {
- //Read Obj from File
- File file = new File("tempFile");
- ObjectInputStream ois = null;
- try {
- ois = new ObjectInputStream(new FileInputStream(file));
- User1 newUser = (User1) ois.readObject();
- System.out.println(newUser);
- } catch (IOException e) {
- e.printStackTrace();
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } finally {
- IOUtils.closeQuietly(ois);
- try {
- FileUtils.forceDelete(file);
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- }
- class User1 implements Serializable {
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
- class User1 implements Serializable {
- private String name;
- private int age;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
- public long getSerialVersionUID() {
- // REMIND: synchronize instead of relying on volatile?
- if (suid == null) {
- suid = AccessController.doPrivileged(
- new PrivilegedAction<Long>() {
- public Long run() {
- return computeDefaultSUID(cl);
- }
- }
- );
- }
- return suid.longValue();
- }
- class="language-text">
- String s = "abcd"; s = s.concat("ef");
- String wechat = "Hollis";
- String introduce = "每日更新 Java 相关技术文章";
- String hollis = wechat + "," + introduce;
- String wechat = "Hollis";
- String introduce = "每日更新 Java 相关技术文章";
- String hollis = wechat.concat(",").concat(introduce);
- StringBuffer
- StringBuffer wechat = new StringBuffer("Hollis");
- String introduce = "每日更新 Java 相关技术文章";
- StringBuffer hollis = wechat.append(",").append(introduce);
- StringBuilder
- StringBuilder wechat = new StringBuilder("Hollis");
- String introduce = "每日更新 Java 相关技术文章";
- StringBuilder hollis = wechat.append(",").append(introduce);
- StringUtils.join
- String wechat = "Hollis";
- String introduce = "每日更新 Java 相关技术文章";
- System.out.println(StringUtils.join(wechat, ",", introduce));
- String []list ={
- "Hollis","每日更新 Java 相关技术文章"
- };
- String result= StringUtils.join(list,",");
- System.out.println(result);
- // 结果: Hollis, 每日更新 Java 相关技术文章
- String wechat = "Hollis";
- String introduce = "每日更新 Java 相关技术文章";
- String hollis = wechat + "," + introduce;
- String wechat = "Hollis";
- String introduce = "\u6BCF\u65E5\u66F4\u65B0Java\u76F8\u5173\u6280\u672F\u6587\u7AE0";// 每日更新 Java 相关技术文章
- String hollis = (new StringBuilder()).append(wechat).append(",").append(introduce).toString();
- public String concat(String str) {
- int otherLen = str.length();
- if (otherLen == 0) {
- return this;
- }
- int len = value.length;
- char buf[] = Arrays.copyOf(value, len + otherLen);
- str.getChars(buf, len);
- return new String(buf, true);
- }
- public StringBuilder append(String str) {
- super.append(str);
- return this;
- }
- public AbstractStringBuilder append(String str) {
- if (str == null)
- return appendNull();
- int len = str.length();
- ensureCapacityInternal(count + len);
- str.getChars(0, len, value, count);
- count += len;
- return this;
- }
- public synchronized StringBuffer append(String str) {
- toStringCache = null;
- super.append(str);
- return this;
- }
- public static String join(final Object[] array, String separator, final int startIndex, final int endIndex) {
- if (array == null) {
- return null;
- }
- if (separator == null) {
- separator = EMPTY;
- }
- // endIndex - startIndex> 0: Len = NofStrings *(len(firstString) + len(separator))
- // (Assuming that all Strings are roughly equally long)
- final int noOfItems = endIndex - startIndex;
- if (noOfItems <= 0) {
- return EMPTY;
- }
- final StringBuilder buf = new StringBuilder(noOfItems * 16);
- for (int i = startIndex; i <endIndex; i++) {
- if (i> startIndex) {
- buf.append(separator);
- }
- if (array[i] != null) {
- buf.append(array[i]);
- }
- }
- return buf.toString();
- }
- long t1 = System.currentTimeMillis();
- // 这里是初始字符串定义
- for (int i = 0; i <50000; i++) {
- // 这里是字符串拼接代码
- }
- long t2 = System.currentTimeMillis();
- System.out.println("cost:" + (t2 - t1));
- + cost:5119
- StringBuilder cost:3
- StringBuffer cost:4
- concat cost:3623
- StringUtils.join cost:25726
- long t1 = System.currentTimeMillis();
- String str = "hollis";
- for (int i = 0; i < 50000; i++) {
- String s = String.valueOf(i);
- str += s;
- }
- long t2 = System.currentTimeMillis();
- System.out.println("+ cost:" + (t2 - t1));
- long t1 = System.currentTimeMillis();
- String str = "hollis";
- for(int i = 0; i < 50000; i++)
- {
- String s = String.valueOf(i);
- str = (new StringBuilder()).append(str).append(s).toString();
- }
- long t2 = System.currentTimeMillis();
- System.out.println((new StringBuilder()).append("+ cost:").append(t2 - t1).toString());
- public static void main(String[] args) {
- // 使用 ImmutableList 初始化一个 List
- List<String> userNames = ImmutableList.of("Hollis", "hollis", "HollisChuang", "H");
- System.out.println("使用 for 循环遍历 List");
- for (int i = 0; i <userNames.size(); i++) {
- System.out.println(userNames.get(i));
- }
- System.out.println("使用 foreach 遍历 List");
- for (String userName : userNames) {
- System.out.println(userName);
- }
- }
- Hollis
- hollis
- HollisChuang
- H
- Hollis
- hollis
- HollisChuang
- H
- Iterator iterator = userNames.iterator();
- do
- {
- if(!iterator.hasNext())
- break;
- String userName = (String)iterator.next();
- if(userName.equals("Hollis"))
- userNames.remove(userName);
- } while(true);
- System.out.println(userNames);
- // 使用双括弧语法 (double-brace syntax) 建立并初始化一个 List
- List<String> userNames = new ArrayList<String>() {{
- add("Hollis");
- add("hollis");
- add("HollisChuang");
- add("H");
- }};
- for (int i = 0; i <userNames.size(); i++) {
- if (userNames.get(i).equals("Hollis")) {
- userNames.remove(i);
- }
- }
- System.out.println(userNames);
- List<String> userNames = new ArrayList<String>() {{
- add("Hollis");
- add("hollis");
- add("HollisChuang");
- add("H");
- }};
- for (String userName : userNames) {
- if (userName.equals("Hollis")) {
- userNames.remove(userName);
- }
- }
- System.out.println(userNames);
- public static void main(String[] args) {
- // 使用 ImmutableList 初始化一个 List
- List<String> userNames = new ArrayList<String>() {{
- add("Hollis");
- add("hollis");
- add("HollisChuang");
- add("H");
- }};
- Iterator iterator = userNames.iterator();
- do
- {
- if(!iterator.hasNext())
- break;
- String userName = (String)iterator.next();
- if(userName.equals("Hollis"))
- userNames.remove(userName);
- } while(true);
- System.out.println(userNames);
- }
- final void checkForComodification() {
- if (modCount != expectedModCount)
- throw new ConcurrentModificationException();
- }
- class ArrayList{
- private int modCount;
- public void add();
- public void remove();
- private class Itr implements Iterator<E> {
- int expectedModCount = modCount;
- }
- public Iterator<E> iterator() {
- return new Itr();
- }
- }
- List<String> userNames = new ArrayList<String>() {{
- add("Hollis");
- add("hollis");
- add("HollisChuang");
- add("H");
- }};
- for (int i = 0; i <1; i++) {
- if (userNames.get(i).equals("Hollis")) {
- userNames.remove(i);
- }
- }
- System.out.println(userNames);
- List<String> userNames = new ArrayList<String>() {{
- add("Hollis");
- add("hollis");
- add("HollisChuang");
- add("H");
- }};
- Iterator iterator = userNames.iterator();
- while (iterator.hasNext()) {
- if (iterator.next().equals("Hollis")) {
- iterator.remove();
- }
- }
- System.out.println(userNames);
- List<String> userNames = new ArrayList<String>() {{
- add("Hollis");
- add("hollis");
- add("HollisChuang");
- add("H");
- }};
- userNames = userNames.stream().filter(userName -> !userName.equals("Hollis")).collect(Collectors.toList());
- System.out.println(userNames);
- List<String> userNames = new ArrayList<String>() {{
- add("Hollis");
- add("hollis");
- add("HollisChuang");
- add("H");
- }};
- for (String userName : userNames) {
- if (userName.equals("Hollis")) {
- userNames.remove(userName);
- break;
- }
- }
- System.out.println(userNames);
- ConcurrentLinkedDeque<String> userNames = new ConcurrentLinkedDeque<String>() {{
- add("Hollis");
- add("hollis");
- add("HollisChuang");
- add("H");
- }};
- for (String userName : userNames) {
- if (userName.equals("Hollis")) {
- userNames.remove();
- }
- }
- public static void main(String[] args) {
- int aHundredMillion = 10000000;
- Map<Integer, Integer> map = new HashMap<>();
- long s1 = System.currentTimeMillis();
- for (int i = 0; i <aHundredMillion; i++) {
- map.put(i, i);
- }
- long s2 = System.currentTimeMillis();
- System.out.println("未初始化容量, 耗时 :" + (s2 - s1));
- Map<Integer, Integer> map1 = new HashMap<>(aHundredMillion / 2);
- long s5 = System.currentTimeMillis();
- for (int i = 0; i <aHundredMillion; i++) {
- map1.put(i, i);
- }
- long s6 = System.currentTimeMillis();
- System.out.println("初始化容量 5000000, 耗时 :" + (s6 - s5));
- Map<Integer, Integer> map2 = new HashMap<>(aHundredMillion);
- long s3 = System.currentTimeMillis();
- for (int i = 0; i <aHundredMillion; i++) {
- map2.put(i, i);
- }
- long s4 = System.currentTimeMillis();
- System.out.println("初始化容量为 10000000, 耗时 :" + (s4 - s3));
- }
- Map<String, String> map = new HashMap<String, String>(1);
- map.put("hahaha", "hollischuang");
- Class mapType = map.getClass();
- Method capacity = mapType.getDeclaredMethod("capacity");
- capacity.setAccessible(true);
- System.out.println("capacity :" + capacity.invoke(map));
- int n = cap - 1;
- n |= n>>> 1;
- n |= n>>> 2;
- n |= n>>> 4;
- n |= n>>> 8;
- n |= n>>> 16;
- return (n <0) ? 1 : (n>= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
- Step 1,5->7
- Step 2,7->8
- Step 1,9->15
- Step 2,15->16
- Step 1,19->31
- Step 2,31->32
- n |= n>>> 1;
- n |= n>>> 2;
- n |= n>>> 4;
- n |= n>>> 8;
- n |= n>>> 16;
- 1100 1100 1100>>>1 = 0110 0110 0110
- 1100 1100 1100 | 0110 0110 0110 = 1110 1110 1110
- 1110 1110 1110>>>2 = 0011 1011 1011
- 1110 1110 1110 | 0011 1011 1011 = 1111 1111 1111
- 1111 1111 1111>>>4 = 1111 1111 1111
- 1111 1111 1111 | 1111 1111 1111 = 1111 1111 1111
- Step 1:
- 0100>>>1 = 0010
- 0100 | 0010 = 0110
- 0110>>>1 = 0011
- 0110 | 0011 = 0111
- Step 2:
- 0111 + 0001 = 1000
- int n = cap - 1;
- n |= n>>> 1;
- n |= n>>> 2;
- n |= n>>> 4;
- n |= n>>> 8;
- n |= n>>> 16;
- return (n <0) ? 1 : (n>= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
- public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) {
- return new HashMap<K, V>(capacity(expectedSize));
- }
- /**
- * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no
- * larger than expectedSize and the load factor is ≥ its default (0.75).
- */
- static int capacity(int expectedSize) {
- if (expectedSize <3) {
- checkNonnegative(expectedSize, "expectedSize");
- return expectedSize + 1;
- }
- if (expectedSize < Ints.MAX_POWER_OF_TWO) {
- // This is the calculation used in JDK8 to resize when a putAll
- // happens; it seems to be the most conservative calculation we
- // can make. 0.75 is the default load factor.
- return (int) ((float) expectedSize / 0.75F + 1.0F);
- }
- return Integer.MAX_VALUE; // any large value
- }
来源: http://www.bubuko.com/infodetail-3035062.html