- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Copy all elements of Java HashSet to an Object Array
Declare a HashSet and add elements −
Set<Integer> hs = new HashSet<Integer>(); hs.add(15); hs.add(71); hs.add(82); hs.add(89); hs.add(91); hs.add(93); hs.add(97); hs.add(99);
To copy all the elements, use the toArray() method −
Object[] obArr = hs.toArray();
The following is an example to copy all elements to HashSet to an object array −
Example
import java.util.*; public class Demo { public static void main(String args[]) { Set<Integer> hs = new HashSet<Integer>(); hs.add(15); hs.add(71); hs.add(82); hs.add(89); hs.add(91); hs.add(93); hs.add(97); hs.add(99); System.out.println("Elements in set = "+hs); System.out.println("Copying all elements..."); Object[] obArr = hs.toArray(); for (Object ob : obArr) System.out.println(ob); } }
Output
Elements in set = [97, 82, 99, 71, 89, 91, 93, 15] Copying all elements... 97 82 99 71 89 91 93 15
Advertisements