Set、List和数组互相转换

java中Set、List和数组互相转换

public class ArraysTest {

  /**
   * 数组转List
   * @param arrays
   * @return
   */
  private static List arraysToList(Object[] arrays) {
    return Arrays.asList(arrays); // 返回一个固定长度的list,不可add和remove,否则会报java.lang.UnsupportedOperationException
    // 如果想要返回可变列表,则需要将数组里的元素遍历加到List中
    /*List list = new ArrayList();
    if (arrays != null && arrays.length > 0) {
      for (Object obj : arrays) {
        list.add(obj);
      }
    }
    return list;*/
  }


  /**
   * 数组转set
   * @param arrays
   * @return
   */
  private static Set arraysToSet(Object[] arrays) {
    return new HashSet(Arrays.asList(arrays)); // 先转成list,再通过HashSet构造出Set
  }

  /**
   * list转数组
   * @param list
   * @return
   */
  private static Object[] listToArrays(List list) {
    return list.toArray();
  }

  /**
   * list转set
   * @param list
   * @return
   */
  private static Set listToSet(List list) {
    return new HashSet(list);
  }

  /**
   * set转数组
   * @param set
   * @return
   */
  private static Object[] setToArray(Set set) {
    return set.toArray();
  }

  /**
   * set转List
   * @param set
   * @return
   */
  private static List setToList(Set set) {
    return new ArrayList(set);
  }
  

  public static void main(String[] args) {
    String[] strArrays = new String[]{"csdn", "ddp", "Roman", "ForEver"};
    List list1 = arraysToList(strArrays);
    Set set = arraysToSet(strArrays);
    Object[] objArrays = listToArrays(list1);
    Set set1 = listToSet(list1);
    Object[] objectArrays2 = setToArray(set1);
    List list2 = setToList(set1);
    System.out.println("sss");
  }
  

  private static void printList(List list) {
    if (list != null && list.size() > 0) {
      for (Object obj : list) {
        System.out.println(obj.toString());
      }
    }
  }
}

你可能感兴趣的:(Java)