0

In hashset, i am able to print the objects added using sysout of obj name and also by iterating and returning the elements. what is the difference? both gives the objects stored in the hash set.

Below is the code :

public static void main(String[] args) {


    HashSet<Integer> hs= new HashSet<Integer>();

    hs.add(12);
    hs.add(234);



    Iterator<Integer> it = hs.iterator();

    while(it.hasNext())
    {
        System.out.println(it.next());
    }
    System.out.println(hs);



}
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Siva
  • 17
  • 7
  • `System.out.println(hs);` internally calls `hs.toString()` which just displays content of the set. Using `it.next()` you're actually accessing specific objects. – Amongalen Mar 04 '20 at 11:55
  • 1
    Why do you think that there is a difference? – Holger Mar 04 '20 at 13:58

1 Answers1

0

Run below code and see can you get name from custom class in sysout

package io.eshu.test;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class TestRandom {

    public static void main(String ad[]) {

        MyClass e = new MyClass();
        e.setName("Test");

        Set<MyClass> c = new HashSet<>();
        c.add(e);

        System.out.println(c);

        Iterator<MyClass> its = c.iterator(); 
        while(its.hasNext()) 
        { 
            System.out.println(its.next().getName()); 
        }
    }
}
class MyClass{
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Printing set in sysout gives you object but in case of wrapper class you get value but with class where toString method is not implemented you will get object hashcode in output. This is the difference and as @Amongalen said you can access specific objects using iterator.

Eshu
  • 499
  • 4
  • 15