Java各種類型之間的互相轉換

/**
 * @author ManaphyChen
 * @date 2019-05-29 19:19
 */
public class TypeConversion {
    public static void main(String[] args) throws ParseException {
        // 1.將字符串轉換爲字符數組
        String str = "Manaphy";
        char[] charArray = str.toCharArray();
        System.out.println(Arrays.toString(charArray)); // [M, a, n, a, p, h, y]
        // 2.將字符數組轉換爲字符串
        str = new String(charArray);
        System.out.println(str); // Manaphy
        // 3.將字符串轉換爲byte數組
        byte[] bytes = str.getBytes(); // 以默認編碼轉換
//		bytes = str.getBytes("GBK"); // 以GBK編碼轉換
        System.out.println(Arrays.toString(bytes)); // [77, 97, 110, 97, 112, 104, 121]
        // 4.將byte數組轉換爲字符串
        str = new String(bytes);
        System.out.println(str); // Manaphy
        // 5.把其他類型數據轉換爲字符串
        int i = 123;
        String txt = "" + i; // 字符串與基本類型數據連接
        txt = String.valueOf(i); // 轉換基本數據類型
        // 6.

        // 7.String、int、Integer的互相轉換
        // int轉Integer
        Integer integer1 = new Integer(10);
        Integer integer2 = Integer.valueOf(10); // 官方推薦這種寫法
        Integer integer3 = 10; // 自動裝箱
        // String轉Integer
        Integer integer4 = Integer.valueOf("10");
        // Integer轉int
        int int1 = integer1.intValue();
        int int2 = integer3; // 自動拆箱
        // int轉String
        String str2 = String.valueOf(int1);
        String str3 = Integer.toString(int2);
        // String轉int
        int int3 = Integer.parseInt(str2);
        // Integer轉String
        String str4 = integer1.toString();

        // 8.String轉換成BigDecimal
        BigDecimal bd = new BigDecimal(str2);
        // 9.String轉化成Date
        String strDate = "2019-04-13";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 將String轉化爲util.Date
        java.util.Date utilDate = sdf.parse(strDate);
        // 將String轉化爲sql.Date
        java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());

        // 10.List,Set,數組之間的轉換
        String[] arr = new String[]{"A", "B", "C"};
        //數組轉List
        List<String> list = Arrays.asList(arr);//長度固定不變
        List<String> list = new ArrayList<>(Arrays.asList(arr));//長度可變
        //List轉Set
        HashSet<String> set = new HashSet<>(list);
        //Set轉List
        ArrayList<String> arrayList = new ArrayList<>(set);
        //數組轉Set-->利用數組轉List再轉Set
        HashSet<String> hashSet = new HashSet<>(Arrays.asList(arr));
        //List轉數組
        Object[] array = list.toArray();
        //Set轉數組
        Object[] arraySet = set.toArray();

    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章