Skip to content

Latest commit

 

History

History
45 lines (33 loc) · 1.27 KB

File metadata and controls

45 lines (33 loc) · 1.27 KB

HashSet转换为List / ArrayList

原文: https://beginnersbook.com/2014/08/convert-hashset-to-a-list-arraylist/

在本教程中,我们将学习如何将HashSet转换为ListArrayList)。

程序

这里我们有一个String元素的HashSet,我们通过将HashSet的所有元素复制到ArrayList来创建一个StringArrayList。以下是完整的代码:

import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
class ConvertHashSetToArrayList{ 
  public static void main(String[] args) {
     // Create a HashSet
     HashSet<String> hset = new HashSet<String>();

     //add elements to HashSet
     hset.add("Steve");
     hset.add("Matt");
     hset.add("Govinda");
     hset.add("John");
     hset.add("Tommy");

     // Displaying HashSet elements
     System.out.println("HashSet contains: "+ hset);

     // Creating a List of HashSet elements
     List<String> list = new ArrayList<String>(hset);

     // Displaying ArrayList elements
     System.out.println("ArrayList contains: "+ list);
  }
}

输出:

HashSet contains: [Tommy, Matt, Steve, Govinda, John]
ArrayList contains: [Tommy, Matt, Steve, Govinda, John]