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.
Studentoutside the for loop, so you end up adding many times the very same instance and changing its nameHashSethas a singleStudentinstance (in fact you invokednew Student()only once). Move it into the for loop.