Java中各种数据类型之间的转换
程序员文章站
2024-02-10 08:32:36
...
在java编程中,经常会遇到数据类型之间转换的问题,下面做一个总结
1、String与Integer之间的转换
string转Integer:
Integer i = Integer.parseInt();
Integer转String
Integer a;
String str = Integer.toString(a);
2、char与Integer之间的转换
char转Integer:
char a='9';
Integer i =(int)a - (int)('0');
Integer转char
Integer i;
char c = (char)i;
3、String与list之间的转换
String转list
String str ="abc";
List<Character> list = new ArrayList<Character>();
for(int i=0;i<str.length();i++){
list.add(str.charAt(i));
}
list转String
String str ="";
List<Character> list = new ArrayList<Character>();
for(int i=0;i<list.size();i++){
str += list.get(i);
}
3、array与list之间的转换
array转list
String[] s = new String[]{"A", "B", "C", "D","E"};
List<String> list = Arrays.asList(s);
list转array
String[] dest = list.toArray(new String[0]);
4、list与set之间的转换
list转set
Set<String> set = new HashSet<>(list);
set转list
List<String> list_1 = new ArrayList<>(set);
5、array与set之间的转换
array转set
s = new String[]{"A", "B", "C", "D","E"};
set = new HashSet<>(Arrays.asList(s));
set转array
dest = set.toArray(new String[0]);
后续遇到还将持续更新