1.自动类型转换:
所谓自动类型转换,是指系统支持把某种基础类型直接付给另一种基础类型的变量。
注意:自动类型转换的前提条件,必须是把表数范围小的数值或变量赋给表数范围大的变量。
其实很好理解,我们都知道数值型类型主要区别是分配的内存空间大小不同,可以想象一杯水往一个容积大的空桶之中倒进,水不会流出来,相反如果一桶水往一个小的空间杯子里面倒进的时候,水就会溢出。
所以java支持自动类型转换如上图所示。
2.强制类型转换:
常用的:
//常用
String转Int:
Integer.parseInt(string);
Int转String:
int MyInt = 1234;
String MyString = "" + MyInt;
double转String:
String string=8.0+"";
//金额数值类型转换保留两位小数,不足0不舍去
NumberFormat numberFormat = new DecimalFormat("###.00");
return numberFormat.format(value);
//金额数值类型转换 保留两位小数
NumberFormat numberFormat = new DecimalFormat("###.##");
return numberFormat.format(value);
//日期类型转换 日期转字符串
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy:MM:dd HH:mm:ss");
String startTimeStr = simpleDateFormat.format(new Date());
//日期类型转换 字符串转类型
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date startTime = simpleDateFormat.parse(startTimeStr);
一些难的:
int[]转list
Arrays.stream(int[]).boxed().collect(Collectors.toList());
eg:
int[] Numbers = formationService.getElementNumbers(userInSession);
List<Integer> elementList = Arrays.stream(Numbers).boxed().collect(Collectors.toList());
String转换为char[]
char[] chars1 = str.toCharArray();
char[]转换为String
String str1 = new String(chars); //通过String构造函数
String str2 = String.valueOf(chars); //通过String类型转换,实际也是new String(char[])
数组和List
List<ClassA> list1 = Arrays.asList(chars); //通过Arrays的工具类
List<ClassA> list2 = new ArrayList<>(); //通过Collections工具类
Collections.addAll(list2,chars);
List转换为包装类型数组
List<ClassA> list = new ArrayList<>();
list.add('1');
list.add('2');
ClassA[] chars = list.toArray(new Character[list.size()]);//注意toArray()的参数
String转List
String str1 = "123456";
//方式一
List<String>list1 = Arrays.asList(str.split("")); //str.split()返回一个String[]数组
//方式二
List<String>list2 = new ArrayList<>();
Collections.addAll(list2, str.split(""))
List转String
public static void listToString(){
List<String> list = Arrays.asList("1","2","3","4");
String str = String.join("", list); //"1234"
}
//String.join 可以添加符号
List和Set互转
List<String> list = new ArrayList<>();
Set<String> set = new HashSet<>(list); //直接构造函数即可
同理,set转list也这样转
当String转set时,先分割成数组,再转list,再变成set.
set转String时,使用String.join()
3.表达式类型自动提升