1.Basic java example program to Copy all elements of Java HashSet to an Object Array
Output:
- Object[] toArray() This method is used To copy all elements of java HashSet object into array use
- package com.copyelementhashset;
- import java.util.HashSet;
- import java.util.Iterator;
- public class HashsetExample{
- public static void main(String[] args) {
- //create object of HashSet
- HashSet<Integer> hashSet = new HashSet();
- //add elements to HashSet object
- hashSet.add(1);
- hashSet.add(2);
- hashSet.add(3);
- hashSet.add(4);
- hashSet.add(5);
- Object[] objArray = hashSet.toArray();
- //display contents of Object array
- System.out.println("HashSet elements are copied into an Array. Now Array Contains..");
- for(int index=0; index < objArray.length ; index++)
- System.out.println(objArray[index]);
- System.out.println("Hashset contains");
- Iterator it=hashSet.iterator();
- while(it.hasNext()){
- System.out.println(it.next());
- }
- }
- }
Output:
- HashSet elements are copied into an Array. Now Array Contains..
- 1
- 2
- 3
- 4
- 5
- Hashset contains
- 1
- 2
- 3
- 4
- 5
Bagikan
Java program to Copy all elements of Java HashSet to an Object Array
4/
5
Oleh
Kris Kimcil