Copy all elements in Java TreeSet to an Object Array

java 8object oriented programmingprogramming

Create a TreeSet and add elements −

TreeSet<String> tSet = new TreeSet<String>();
tSet.add("TV");
tSet.add("Radio");
tSet.add("Internet");

Now, let us copy it to object array −

Object[] arr = tSet.toArray();
for (Object ob: arr) {
   System.out.println(ob);
}

The following is an example to copy all elements in TreeSet to an Object Array −

示例

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> tSet = new TreeSet<String>();
      tSet.add("TV");
      tSet.add("Radio");
      tSet.add("Internet");
      System.out.println("TreeSet elements = "+tSet);
      Object[] arr = tSet.toArray();
      for (Object ob: arr) {
         System.out.println(ob);
      }
   }
}

输出

TreeSet elements = [Internet, Radio, TV]
Internet
Radio
TV

相关文章