Setset = new HashSet<>(); set.add("apple"); set.add("banana"); set.add("cherry"); Object[] array = set.toArray(); for(Object o : array) { System.out.println(o); }
SetThis code snippet creates a TreeSet of integers and adds three numbers to it. The Set.toArray(Integer[]) method is called to convert the set to an array of type Integer[]. The for-each loop is used to print each element in the array. Both examples use the Set interface and are part of the Java Collections Framework. The Set interface is located in the java.util package.set = new TreeSet<>(); set.add(5); set.add(2); set.add(10); Integer[] array = set.toArray(new Integer[set.size()]); for(Integer i : array) { System.out.println(i); }