Método SortedSet toArray() en Java con ejemplos

El método toArray() de Java SortedSet se utiliza para formar una array de los mismos elementos que la de SortedSet. Básicamente, copia todo el elemento de un SortedSet a una nueva array.

Sintaxis:

Object[] toArray()

Parámetros: El método no toma ningún parámetro.

Valor devuelto: el método devuelve una array que contiene los elementos similares a SortedSet.

Nota : El método toArray() en SortedSet se hereda de la interfaz Set en Java.

Los siguientes programas ilustran el método SortedSet.toArray():

Programa 1:

// Java code to illustrate toArray()
  
import java.util.*;
  
public class SortedSetDemo {
    public static void main(String args[])
    {
  
        // Creating an empty SortedSet
        SortedSet<String> abs_col
            = new TreeSet<String>();
  
        // Use add() method to add
        // elements into the SortedSet
        abs_col.add("Welcome");
        abs_col.add("To");
        abs_col.add("Geeks");
        abs_col.add("For");
        abs_col.add("Geeks");
  
        // Displaying the Set
        System.out.println("The SortedSet: "
                           + abs_col);
  
        // Creating the array and using toArray()
        Object[] arr = abs_col.toArray();
  
        System.out.println("The array is:");
        for (int j = 0; j < arr.length; j++)
            System.out.println(arr[j]);
    }
}
Producción:

The SortedSet: [For, Geeks, To, Welcome]
The array is:
For
Geeks
To
Welcome

Programa 2:

// Java code to illustrate toArray()
  
import java.util.*;
  
public class SetDemo {
    public static void main(String args[])
    {
        // Creating an empty SortedSet
        SortedSet<Integer> abs_col
            = new TreeSet<Integer>();
  
        // Use add() method to add
        // elements into the SortedSet
        abs_col.add(10);
        abs_col.add(15);
        abs_col.add(30);
        abs_col.add(20);
        abs_col.add(5);
        abs_col.add(25);
  
        // Displaying the SortedSet
        System.out.println("The SortedSet: "
                           + abs_col);
  
        // Creating the array and using toArray()
        Object[] arr = abs_col.toArray();
  
        System.out.println("The array is:");
        for (int j = 0; j < arr.length; j++)
            System.out.println(arr[j]);
    }
}
Producción:

The SortedSet: [5, 10, 15, 20, 25, 30]
The array is:
5
10
15
20
25
30

Referencia : https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#toArray()

Publicación traducida automáticamente

Artículo escrito por gopaldave y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *