Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
AbstractSet toArray() method in Java with Example
Next article icon

AbstractSet toArray(T[]) method in Java with Example

Last Updated : 24 Dec, 2018
Comments
Improve
Suggest changes
Like Article
Like
Report

The toArray(T[]) method method of AbstractSet class in Java is used to form an array of the same elements as that of the AbstractSet. It returns an array containing all of the elements in this AbstractSet in the correct order; the run-time type of the returned array is that of the specified array. If the AbstractSet 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 AbstractSet.
If the AbstractSet fits in the specified array with room to spare (i.e., the array has more elements than the AbstractSet), the element in the array immediately following the end of the AbstractSet is set to null. (This is useful in determining the length of the AbstractSet only if the caller knows that the AbstractSet does not contain any null elements.)

Syntax:

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

Parameters: The method accepts one parameter arr[] which is the array into which the elements of the AbstractSet 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 AbstractSet.

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 AbstractSet.
  • NullPointerException: If the array is Null, then this exception is thrown.

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

Program 1: When array is of the size of AbstractSet




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

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




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

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




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

Program 4: To demonstrate NullPointerException




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


Next Article
AbstractSet toArray() method in Java with Example

C

code_r
Improve
Article Tags :
  • Java
  • Java - util package
  • Java-AbstractSet
  • Java-Collections
  • Java-Functions
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

  • AbstractSet toArray() method in Java with Example
    The toArray() method of Java AbstractSet is used to form an array of the same elements as that of the AbstractSet. Basically, it copies all the element from a AbstractSet to a new array. Syntax: Object[] arr = AbstractSet.toArray() Parameters: The method does not take any parameters. Return Value: T
    2 min read
  • AbstractSequentialList toArray(T[]) method in Java with Example
    The toArray(arr[]) method of AbstractSequentialList class in Java is used to form an array of the same elements as that of the AbstractSequentialList. It returns an array containing all of the elements in this AbstractSequentialList in the correct order; the run-time type of the returned array is th
    4 min read
  • AbstractSet toString() method in Java with Example
    The toString() method of Java AbstractSet is used to return a string representation of the elements of the Collection. The String representation comprises a set representation of the elements of the Collection in the order they are picked by the iterator closed in square brackets[].This method is us
    2 min read
  • AbstractSequentialList toArray() method in Java with Example
    The toArray() method of Java AbstractSequentialList is used to form an array of the same elements as that of the AbstractSequentialList. Basically, it copies all the element from a AbstractSequentialList to a new array. Syntax: Object[] arr = AbstractSequentialList.toArray() Parameters: The method d
    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 par
    3 min read
  • AbstractSet size() method in Java with Example
    The size() method of AbstractSet in Java is used to get the size for this instance of the AbstractSet. It returns an integer value which is the size for this instance of the AbstractSet. Syntax: public int size() Parameters: This function has no parameters. Returns: The method returns an integer val
    2 min read
  • Stack toArray() method in Java with Example
    The toArray() method of Stack class in Java is used to form an array of the same elements as that of the Stack. Basically, it copies all the element from a Stack to a new array. Syntax: Object[] arr = Stack.toArray() Parameters: The method does not take any parameters. Return Value: The method retur
    2 min read
  • AbstractList subList() method in Java with Examples
    The subList() method of java.util.AbstractList class is used to return a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. (If fromIndex and toIndex are equal, the returned list is empty.) The returned list is backed by this list, so non-structural
    3 min read
  • CopyOnWriteArraySet toArray() method in Java with Example
    toArray() The Java.util.concurrent.CopyOnWriteArraySet.toArray() method returns an array containing all the elements in the set in proper sequence i.e. from first to last. The returned array will be safe as a new array is created (hence new memory is allocated). Thus the caller is free to modify the
    3 min read
  • AbstractList get() method in Java with Examples
    The get() method of java.util.AbstractList class is used to return the element at the specified position in this list. Syntax: public abstract E get(int index) Parameters: This method takes index of the element as a parameter, the element at which is to be returned. Returns Value: This method return
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences