-1

I'm trying to create objects of a class and trying to store it in Hashset which is working fine. But when I'm trying to print it, it's showing some weird values like "com.hashset2.java.Driver$TemplateSet@30f39991". In debugging console I saw the values were inserted correct. Here is my code:

package com.hashset.java;

import java.util.HashSet;
import java.util.Scanner;

public class Driver {

public static void main(String[] args) {

    HashSet<TemplateSet> numberSet = new HashSet<TemplateSet>();

    Scanner scanner = new Scanner(System.in);

    int n = scanner.nextInt();

    for (int i = 0; i < n; i++)
    {
        int a, b;

        a = scanner.nextInt();
        b = scanner.nextInt();

        numberSet.add(new TemplateSet(a, b));
    }
}

public static class TemplateSet {

    int n1, n2;

    TemplateSet(int num1, int num2)
    {
        this.n1 = num1;
        this.n2 = num2;
    }
 }
}

This is a sample output enter image description here

2 Answers2

0
public static class TemplateSet {

    int n1, n2;

    TemplateSet(int num1, int num2)
    {
        this.n1 = num1;
        this.n2 = num2;
    }

 //The toString() method is used by your print statement to convert Object to String format
  @Override
  public String toString()
  {
    return n1+","+n2;
  }
 }
Sync it
  • 1,180
  • 2
  • 11
  • 29
-1
// Java program to print the elements
// of HashSet using iterator cursor

import java.util.*;

class GFG {
    public static void main(String[] args)
    {

        HashSet<Integer> hs = new HashSet<Integer>();
        hs.add(5);
        hs.add(2);
        hs.add(3);
        hs.add(6);
        hs.add(null);

        // print HashSet elements one by one.
        // Inserton order in not preserved and it is based
        // on hash code of objects.

        // creates Iterator oblect.
        Iterator itr = hs.iterator();

        // check element is present or not. if not loop will
        // break.
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}
Harsh2720
  • 1
  • 2