Java中数组,List,Set的相互转换注意点(样例)

2,435 阅读2分钟
原文链接: click.aliyun.com

摘要: 一,突然想起了,贴个图先 二,样例import java.util.ArrayList;import java.util.Arrays;import java.util.HashSet;import java.

一,突然想起了,贴个图先
image

二,样例
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.google.common.primitives.Ints;

public class SmallProgram
{

public static void transfArrayListSet(int[] a, String[] b){
    //========1,数组转换成list asList
    //①对非简单类型数组而言:转换后的list不能进行修改长度操作,否则会抛出java.lang.UnsupportedOperationException异常(因为asList返回的是一个视图,即:所有list的操作都会反应在原数组上,且这个list是定长的)
    List<String> arr2List4Str = Arrays.asList(b);
    //copyB.add("There will be an ERROR : UnsupportedOperationException");
    //copyB.remove(0);//UnsupportedOperationException
    
    //②对简单类型而言:不能把基本数据类型转换成列表,这里转的时候结果列表里面只有一个int[]类型的数组元素,String等复杂数据类型是可以这样使用的
    //List<int[]> copyA1 = Arrays.asList(a);
    //基本数据类型转换可以使用google的guava下面Ints类的方法,但是转换后的list不能进行修改长度操作,否则会抛出java.lang.UnsupportedOperationException异常(因为asList返回的是一个视图,即:所有list的操作都会反应在原数组上,且这个list是定长的)
    List<Integer> arr2List4Int = Ints.asList(a);
    //copyA2.add(1);//UnsupportedOperationException
    //copyA2.remove(0);//UnsupportedOperationException
    
    //========2,list转数组 toArray
    Object[] list2Arr = arr2List4Int.toArray();
    System.out.println(list2Arr[0]);
    
    //========3,数组转set 通过list中转
    Set<String> arr2Set4Str = new HashSet<String>(Arrays.asList(b));
    arr2Set4Str.add("5");
    arr2Set4Str.remove(0);
    Set<Integer> arr2Set4Int = new HashSet<Integer>(Ints.asList(a));
    arr2Set4Int.add(5);
    arr2Set4Int.remove(0);
    
    //========4,set转数组 toArray
    Object[] set2Arr4Str = arr2Set4Str.toArray();
    Object[] set2Arr4Int = arr2Set4Int.toArray();
    
    //========5,set转list 通过构造方法
    List<String> set2List4Str = new ArrayList<String>(arr2Set4Str);
    set2List4Str.add("6");
    set2List4Str.remove(0);
    List<Integer> set2List4Int = new ArrayList<Integer>(arr2Set4Int);
    set2List4Int.add(6);
    set2List4Int.remove(0);
    
    //========6,list转set 通过构造方法
    Set<String> list2Set4Str = new HashSet<String>(set2List4Str);
    Set<Integer> list2Set4Int = new HashSet<Integer>(set2List4Int);
}

/**
 * @param args
 */
public static void main(String[] args)
{
    int[] intArr = new int[]{1,2,3};
    String[] strArr = new String[]{"1","2","3"};
    SmallProgram. transfArrayListSet(intArr,strArr);
}

}