java

HashSet in java


I am studying programming using Java, and I facing a problem with java.util.HashSet. How to show the size() in HashSet? This my code?

package name;
public class Student
{
   private String name;
   public String getName()
   {
      return this.name;
   }
   public void setName(String name)
   {
     this.name = name;
   }
}
// Entry Point
package client;
import name.Student;
import java.util.Set;
import java.util.HashSet;
import java.util.Scanner;
public class Client1
{
    public static void main (String[] args)
    {
       Scanner scan = new Scanner(System.in);
       Set<Student> students = new HashSet<Student>();
       Student student = new Student();

       int totalStudent = 0;
       System.out.print("TypeTotal Student : ");
       totalStudent = Integer.parseInt(scan.nextLine());
       
       for(int i = 0; i < totalStudent ; i++)
       {
           System.out.print("Name : ");
           String name = scan.nextLine();
           student.setName(name);
           students.add(student);
       }
       System.out.println("Element Total In Set :" students.size());
       for(Student std: students)
       {
           System.out.println(std.getName());
       }
    }
}

If I run this code in terminal, student.size() is not increasing. I need advice.


Solution

  • In your code, Student student is a reference to exactly one object (ever). Since you do not allocate a new Student each time you add an object to the students set, you are, instead, adding the same object to the Set multiple times.

    Note that I used the words "same object" and "Set". A Set allows no more than one instance of an object.

    Your code is pretending to add multiple students, but is actually only adding one student.

    The solution is as follows:

     // really add a student to the set.
     System.out.print("Name : ");
     String name = scan.nextLine();
     student = new Student();// note this line.
     student.setName(name);
     students.add(student);