The Wayback Machine - https://web.archive.org/web/20241119075944/https://www.geeksforgeeks.org/abstractcollection-toarray-method-in-java-with-examples/
Open In App

AbstractCollection toArray() Method in Java with Examples

Last Updated : 26 Nov, 2018
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

1. toArray()

The toArray() method of Java AbstractCollection is used to form an array of the same elements as that of the AbstractCollection. Basically, it copies all the element from a AbstractCollection to a new array.

Syntax:

Object[] arr = AbstractCollection.toArray()

Parameters: The method does not take any parameters.

Return Value: The method returns an array containing the elements similar to the AbstractCollection.

Below programs illustrate the AbstractCollection.toArray() method:

Program 1:




// Java code to illustrate toArray()
  
import java.util.*;
  
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
        // Creating an empty AbstractCollection
        AbstractCollection<String>
            abs_col = new PriorityQueue<String>();
  
        // Use add() method to add
        // elements into the AbstractCollection
        abs_col.add("Welcome");
        abs_col.add("To");
        abs_col.add("Geeks");
        abs_col.add("For");
        abs_col.add("Geeks");
  
        // Displaying the AbstractCollection
        System.out.println("The AbstractCollection: "
                           + 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]);
    }
}


Output:

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

Program 2:




// Java code to illustrate toArray()
  
import java.util.*;
  
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
        // Creating an empty AbstractCollection
        AbstractCollection<Integer>
            abs_col = new PriorityQueue<Integer>();
  
        // Use add() method to add
        // elements into the AbstractCollection
        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 AbstractCollection
        System.out.println("The AbstractCollection: "
                           + 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]);
    }
}


Output:

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

2. toArray(arr[])

The toArray(arr[]) method method of AbstractCollection class in Java is used to form an array of the same elements as that of the AbstractCollection. It returns an array containing all of the elements in this AbstractCollection in the correct order; the run-time type of the returned array is that of the specified array. If the AbstractCollection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the run time type of the specified array and the size of this AbstractCollection.
If the AbstractCollection fits in the specified array with room to spare (i.e., the array has more elements than the AbstractCollection), the element in the array immediately following the end of the AbstractCollection is set to null. (This is useful in determining the length of the AbstractCollection only if the caller knows that the AbstractCollection does not contain any null elements.)

Syntax:

Object[] arr1 = AbstractCollection.toArray(arr[])

Parameters: The method accepts one parameter arr[] which is the array into which the elements of the AbstractCollection are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Return Value: The method returns an array containing the elements similar to the AbstractCollection.

Exception: The method might throw two types of exception:

  • ArrayStoreException: When the mentioned array is of the different type and is not able to compare with the elements mentioned in the AbstractCollection.
  • NullPointerException: If the array is Null, then this exception is thrown.

Below program illustrates the working of the AbstractCollection.toArray(arr[]) method.

Program 1: When array is of the size of AbstractCollection




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


Output:

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

Program 2: When array is less than the size of AbstractCollection




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


Output:

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

Program 3: When array is more than the size of AbstractCollection




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


Output:

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

Program 4: To demonstrate NullPointerException




// Java code to illustrate toArray(arr[])
  
import java.util.*;
  
public class AbstractCollectionDemo {
    public static void main(String args[])
    {
        // Creating an empty AbstractCollection
        AbstractCollection<String>
            abs_col = new PriorityQueue<String>();
  
        // Use add() method to add
        // elements into the AbstractCollection
        abs_col.add("Welcome");
        abs_col.add("To");
        abs_col.add("Geeks");
        abs_col.add("For");
        abs_col.add("Geeks");
  
        // Displaying the AbstractCollection
        System.out.println("The AbstractCollection: "
                           + abs_col);
  
        try {
            // Creating the array
            String[] arr = null;
            // using toArray()
            // Since arr is null
            // Hence exception will be thrown
            arr = abs_col.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);
        }
    }
}


Output:

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


Previous Article
Next Article

Similar Reads

AbstractCollection clear() Method in Java with Examples
The clear() method of Java AbstractCollection in Java is used to remove all of the elements from the Collection. Using the clear() method only clears all the element from the collection and does not delete the collection. In other words, it can be said that the clear() method is used to only empty an existing AbstractCollection. Syntax: AbstractCol
2 min read
AbstractCollection addAll() Method in Java with Examples
The addAll(Collection C) method of Java AbstractCollection is used to append all of the elements from a mentioned collection to this collection. The elements are added randomly without following any specific order. Syntax: boolean addAll(Collection C) Parameters: The parameter C is a collection of any type that is to be added to the collection. Ret
2 min read
AbstractCollection add() Method in Java with Examples
The add() method in Java AbstractCollection is used to add a specific element into a Collection. This method will add the element only if the specified element is not present in the Collection else the function will return False if the element is already present in the Collection. Syntax: AbstractCollection.add(Object element) Parameters: The param
2 min read
AbstractCollection isEmpty() Method in Java with Examples
The isEmpty() method of Java AbstractCollection is used to check and verify if a Collection is empty or not. It returns True if the Collection is empty else it returns False. Syntax: AbstractCollection.isEmpty() Parameters: The method does not take any parameter. Return Value: The function returns True if the collection is empty else it returns Fal
2 min read
AbstractCollection size() Method in Java with Examples
The size() method of Java AbstractCollection is used to get the size of the Collection or the number of elements present in the Collection.Syntax: AbstractCollection.size() Parameters: The method does not take any parameter.Return Value: The method returns the size or the number of elements present in the collection.Below programs illustrates the u
2 min read
AbstractCollection remove() Method in Java with Examples
The remove(Object O) method of Java AbstractCollection is to remove a particular element from a Collection. Syntax: AbstractCollection.remove(Object O) Parameters: The parameter O is of the type of Collection and specifies the element to be removed from the collection. Return Value: This method returns True if the element specified in the parameter
2 min read
AbstractCollection contains() Method in Java with Examples
The contains() method of Java AbstractCollection is used to check whether an element is present in a Collection or not. It takes the element as a parameter and returns True if the element is present in the collection.Syntax: AbstractCollection.contains(Object element) Parameters: The parameter element is of type Collection. This parameter refers to
2 min read
AbstractCollection containsAll() Method in Java with Examples
The containsAll() method of Java AbstractCollection is used to check whether two Collections contain the same elements or not. It takes one collection as a parameter and returns True if all of the elements of this collection is present in the other collection. Syntax: AbstractCollection.containsAll(Collection C) Parameters: The parameter C is a Col
2 min read
AbstractCollection toString() method in Java with Examples
The toString() method of JavaAbstractClass is used to return a string representation of the elements of the Collection. The String representation comprises a list representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is used mainly to display collections other than Stri
2 min read
AbstractCollection in Java with Examples
The AbstractCollection class in Java is a part of the Java Collection Framework and implements the Collection interface. It is used to implement an unmodifiable collection, for which one needs to only extend this AbstractCollection Class and implement only the iterator and the size methods. Class Hierarchy: java.lang.Object ↳ java.util ↳ Class Abst
3 min read
AbstractCollection removeAll() method in Java with Example
The Java.util.AbstractCollection.removeAll(Collection col) method is used to remove all the elements from the AbstractCollection, present in the collection specified. Syntax: AbstractCollection.removeAll(Collection col) Parameters: This method accepts a mandatory parameter col which is the collection whose elements are to be removed from the Abstra
2 min read
Vector toArray() Method in Java with Examples
1. toArray() The toArray() method of Vector class in Java is used to form an array of the same elements as that of the Vector. Basically, it copies all the element from a Vector to a new array. Syntax: Object[] arr = Vector.toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array containing elements s
5 min read
DelayQueue toArray() method in Java with Examples
The toArray() method of DelayQueue is used to return an array containing all the elements in DelayQueue. There elements are not in any specific order in the array.Syntax: public Object[] toArray () or public T[] toArray (T[] a) Parameters: This method either accepts no parameters or it takes an array T[] a as parameter which is the array into which
4 min read
Java Guava | Booleans.toArray() method with Examples
The toArray() method of Booleans Class in the Guava library is used to convert the boolean values, passed as the parameter to this method, into a Boolean Array. These boolean values are passed as a Collection to this method. This method returns a Boolean array. Syntax: public static boolean[] toArray(Collection<Boolean> collection) Parameters
2 min read
Java Guava | Bytes.toArray() method with Examples
The toArray() method of Bytes Class in the Guava library is used to convert the byte values, passed as the parameter to this method, into a Byte Array. These byte values are passed as a Collection to this method. This method returns a Byte array. Syntax: public static byte[] toArray(Collection<? extends Number> collection) Parameters: This me
2 min read
Java Guava | Longs.toArray() method with Examples
The toArray() method of Longs Class in the Guava library is used to convert the long values, passed as the parameter to this method, into a Long Array. These long values are passed as a Collection to this method. This method returns a Long array. Syntax: public static long[] toArray(Collection<? extends Number> collection) Parameters: This me
2 min read
Java Guava | Chars.toArray() method with Examples
The toArray() method of Chars Class in the Guava library is used to convert the char values, passed as the parameter to this method, into a Char Array. These char values are passed as a Collection to this method. This method returns a Char array. Syntax: public static char[] toArray(Collection<Character> collection) Parameters: This method ac
2 min read
Java Guava | Doubles.toArray() method with Examples
The toArray() method of Doubles Class in the Guava library is used to convert the double values, passed as the parameter to this method, into a Double Array. These double values are passed as a Collection to this method. This method returns a Double array. Syntax: public static double[] toArray(Collection<? extends Number> collection) Paramet
2 min read
Java Guava | Floats.toArray() method with Examples
The toArray() method of Floats Class in the Guava library is used to convert the float values, passed as the parameter to this method, into a Float Array. These float values are passed as a Collection to this method. This method returns a Float array. Syntax: public static float[] toArray(Collection<? extends Number> collection) Parameters: T
2 min read
Java Guava | Shorts.toArray() method with Examples
The toArray() method of Shorts Class in the Guava library is used to convert the short values, passed as the parameter to this method, into a Short Array. These short values are passed as a Collection to this method. This method returns a Short array. Syntax: public static short[] toArray(Collection<? extends Number> collection) Parameters: T
2 min read
LinkedTransferQueue toArray() method in Java with Examples
public Object[] toArray() The toArray() method of Java.util.concurrent.LinkedTransferQueue is an in-built function is Java which is used to form an array of the same elements as that of LinkedTransferQueue. Basically, it copies all the element to the new array from the LinkedTransferQueue. Syntax: public Object[] toArray() Parameters: This method d
3 min read
SortedSet toArray() method in Java with Examples
The toArray() method of Java SortedSet is used to form an array of the same elements as that of the SortedSet. Basically, it copies all the element from a SortedSet to a new array. Syntax: Object[] toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array containing the elements similar to the SortedSe
2 min read
ArrayList toArray() method in Java with Examples
The toArray() method of ArrayList is used to return an array containing all the elements in ArrayList in the correct order. Declaring toArray() methodpublic Object[] toArray() or public <T> T[] toArray(T[] a)Parameters: This method either accepts no parameters or it takes an array T[] as a parameter which is the array into which the elements
3 min read
PriorityQueue toArray() Method in Java
The java.util.PriorityQueue.toArray() method in Java is used to form an array of the same elements as that of the Priority Queue. Basically, it copies all the element from a priority queue to a new array. Syntax: Object[] arr = Priority_Queue.toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array co
3 min read
ArrayDeque toArray() Method in Java
The java.util.ArrayDeque.toArray() method is used to form an array of the same elements as that of the Deque. Basically, the method copies all the element from this deque to a new array. Syntax: Object[] arr = Array_Deque.toArray() Parameters: The method does not take any parameters. Return Value: The method returns an array containing the elements
2 min read
ArrayBlockingQueue toArray() Method in Java
The toArray() method of ArrayBlockingQueue class: The toArray() method of ArrayBlockingQueue class is used to create an array containing the same elements as that of this ArrayBlockingQueue, in proper sequence. Basically, it copies all the element from the ArrayBlockingQueue to a new array. This method behaves as a bridge between array and collecti
3 min read
LinkedBlockingQueue toArray() method in Java
toArray() The toArray method of LinkedBlockingQueue is used to create an array having the same elements as that of this LinkedBlockingQueue, in proper sequence. Actually, this method copies all the elements from the LinkedBlockingQueue to a new array. This method behaves as a bridge between array and LinkedBlockingQueue. Syntax: public Object[] toA
5 min read
PriorityBlockingQueue toArray() method in Java
toArray() The toArray method of PriorityBlockingQueue is used to create an array having the same elements as that of this PriorityBlockingQueue, in proper sequence. Actually, this method copies all the element from the PriorityBlockingQueue to a new array. This method behaves as a bridge between array and PriorityBlockingQueue. Syntax: public Objec
5 min read
ConcurrentLinkedQueue toArray() Method in Java
toArray() : The toArray() method of ConcurrentLinkedQueue is used to returns an array of the same elements as that of the ConcurrentLinkedQueue in proper sequence. Basically, it copies all the element from a ConcurrentLinkedQueue to a new array. This method behaves as a bridge between array and ConcurrentLinkedQueue. Syntax: public Object[] toArray
4 min read
CopyOnWriteArrayList toArray() method in Java
The toArray() method of CopyOnWriteArrayList is used to return an array containing all the elements in CopyOnWriteArrayList in the correct order. Syntax: public Object[] toArray() or public <T> T[] toArray(T[] a) Parameters: This method either accepts no parameters or it takes an array T[] a as parameter which is the array into which the elem
2 min read
three90RightbarBannerImg