Método TreeSet toArray (T []) en Java con ejemplo

El método toArray(T[]) de la clase TreeSet en Java se utiliza para formar una array de los mismos elementos que la de TreeSet. Devuelve una array que contiene todos los elementos de este TreeSet en el orden correcto; el tipo de tiempo de ejecución de la array devuelta es el de la array especificada. Si el TreeSet cabe en la array especificada, se devuelve allí. De lo contrario, se asigna una nueva array con el tipo de tiempo de ejecución de la array especificada y el tamaño de este TreeSet.
Si el TreeSet cabe en la array especificada con espacio de sobra (es decir, la array tiene más elementos que el TreeSet), el elemento de la array que sigue inmediatamente al final del TreeSet se establece en nulo. (Esto es útil para determinar la longitud del TreeSet solo si la persona que llama sabe que el TreeSet no contiene ningún elemento nulo).

Sintaxis:

public <T> T[] toArray(T[] a)

Parámetros: El método acepta un parámetro arr[] que es la array en la que se almacenarán los elementos del TreeSet, si es lo suficientemente grande; de lo contrario, se asigna una nueva array del mismo tipo de tiempo de ejecución para este propósito.

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

Excepción: el método puede generar dos tipos de excepción:

  • ArrayStoreException : cuando la array mencionada es de un tipo diferente y no se puede comparar con los elementos mencionados en el TreeSet.
  • NullPointerException : si la array es nula, se lanza esta excepción.

El siguiente programa ilustra el funcionamiento del método TreeSet.toArray(arr[]).

Programa 1: cuando la array es del tamaño de TreeSet

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

The TreeSet: [For, Geeks, To, Welcome]
The arr[] is:
For
Geeks
To
Welcome
null

Programa 2: cuando la array es menor que el tamaño de TreeSet

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

The TreeSet: [For, Geeks, To, Welcome]
The arr[] is:
For
Geeks
To
Welcome

Programa 3: cuando la array es mayor que el tamaño de TreeSet

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

The TreeSet: [For, Geeks, To, Welcome]
The arr[] is:
For
Geeks
To
Welcome
null
null
null
null
null
null

Programa 4: Para demostrar NullPointerException

// Java code to illustrate toArray(arr[])
  
import java.util.*;
  
public class TreeSetDemo {
    public static void main(String args[])
    {
        // Creating an empty TreeSet
        TreeSet<String>
            set = new TreeSet<String>();
  
        // Use add() method to add
        // elements into the TreeSet
        set.add("Welcome");
        set.add("To");
        set.add("Geeks");
        set.add("For");
        set.add("Geeks");
  
        // Displaying the TreeSet
        System.out.println("The TreeSet: "
                           + set);
  
        try {
            // Creating the array
            String[] arr = null;
            // using toArray()
            // Since arr is null
            // Hence exception will be thrown
            arr = set.toArray(arr);
  
            // Displaying arr
            System.out.println("The arr[] is:");
            for (int j = 0; j < arr.length; j++)
                System.out.println(arr[j]);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
Producción:

The TreeSet: [For, Geeks, To, Welcome]
Exception: java.lang.NullPointerException

Publicación traducida automáticamente

Artículo escrito por Code_r 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 *