JAVA中集合(List、HashSet)与数组的转换(Array)
1、list与Array之间的转换
/**
* 1、将数组转为list集合
* 数组转为List集合,通过Arrays工具类中的asList()方法将数组转为List集合
* @param strs 传入的数组
* @return 返回的List集合
*/
public static List<String> arrayToList(String[] strs){
List<String> ls = new ArrayList<>(strs.length);
ls = Arrays.asList(strs);
return ls;
}
/**
* 2、将List集合转化为数组
* 将List集合转换为数组,通过List集合总的toArray()方法即可。
* @param list 传入List集合
* @return 返回的数组
*/
public static String[] listToArray(List list){
String[] strs = (String[]) list.toArray(new String[0]);
return strs;
}
2、List与HashSet之间的转换
/**
* 1、将List集合转化为HashSet集合
* @param hashSet 存入的HashSet集合
* @return 返回List集合
*/
public static List<String> listToHashSet(Set<String> hashSet){
return new ArrayList<>(hashSet);
}
/**
* 2、将HashSet集合转化为List集合
* @param list 存入的List集合
* @return 返回HashSet集合
*/
public static Set<String> hashSetToList(List<String> list){
return new HashSet<>(list);
}
3、Array与HashSet之间的转换
/**
* 1、数组转化为HashSet,将数组通过Arrays工具类中的asList方法将数组转化为集合在进行转化即可
* @param strs 传入的数组
* @return 返回集合
*/
public static Set<String> arrayToSet(String[] strs){
return new HashSet<String>(Arrays.asList(strs));
}
/**
* 2、hashSet转化为数组,通过集合的toArray()方法
* @param hashSet 传入的HashSet集合
* @return 返回数组
*/
public static String[] setToArray(Set<String> hashSet){
return (String[]) hashSet.toArray();
}
总结
array转化为List集合,通过Arrays工具类中的asList()方法;集合转化为数组,通过调用集合类中的toArray()方法即可。
注意
如果arr 是int[] 或者是其他原始类型的数组 那么不能直接用Arrays.asList()进行转化