java 写法推荐

1. for循环

         // 1
         for (int i = 0; i < list.size(); i++) {
            int item = list.get(i);
            System.out.println("这是第" + (i+1) + "个:值为:" + item);
        }

        // 2
        int j = 0;
        for (int i : list) {
            ++j;
            System.out.println("这是第" + j + "个:值为:" + i);
        }

推荐写法2

2. HashMap遍历

    Map<String,String> map=new HashMap<String,String>();
        map.put("1", "value1");
        map.put("2", "value2");
        map.put("3", "value3");
        map.put("4", "value4");
//第三种:推荐,尤其是容量大时 System.out.println(" 通过Map.entrySet遍历key和value"); for(Map.Entry<String, String> entry: map.entrySet()) { System.out.println("Key: "+ entry.getKey()+ " Value: "+entry.getValue()); }

3. 使用log4j的时候如何输出printStackTrace()的堆栈信息

log.error(e.getMessage(),e)

4. String拼接

StringBuilder tmpStr= new StringBuilder();
tmpStr.append(tmpStr1).append(tmpStr2).append(tmpStr3);
String aimStr = tmpStr.toString();

5. 多维数组

package com.example.ch6_2;

public class testArray {
    static final int[][][] THREEARRAY = new int[][][] {
        {{1, 2}, {11, 12, 13}},
        {{2}, {9, 10}},
        {{6, 7}, {14, 16}},
        {{6}, {9, 10}},
    };

    static final int[][] TWOARRAY = new int[][] {
        {1, 2},
        {11, 12, 13}
    };

    static final int[] ONEARRAY = new int[] {1, 2, 11, 12, 15};

    public static void main(String[] argv) {
        System.out.println("
ONEARRAY:");
        for (int oneKey : ONEARRAY) {
            System.out.println(oneKey);
        }

        System.out.println("
TWOARRAY:");
        for (int[] oneKey : TWOARRAY) {
            for (int key : oneKey) {
                System.out.print(key);
            }
            System.out.println();
        }

        System.out.println("
THREEARRAY:");
        for (int[][] oneKey : THREEARRAY) {
            for (int[] key : oneKey) {
                for (int tmp : key) {
                    System.out.print(tmp);
                }
                System.out.println();
            }
            System.out.println("
");
        }
    }
}

结果

ONEARRAY:
1
2
11
12
15

TWOARRAY:
12
111213

THREEARRAY:
12
111213


2
910


67
1416


6
910



Process finished with exit code 0

  

原文地址:https://www.cnblogs.com/kaituorensheng/p/6790035.html