如果我试图添加超过2个数据,它会显示除了

时间:2016-12-07 03:00:42

标签: java

我的程序是将一些数据添加到HashSet但它显示的是concurrentexception这是代码

package com.jspiders.arrays;

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

public class Smain {

/**
 * @param args
 */
static HashSet hs1;
public static void addstudent(int id,String name,double marks) 
{
    Iterator ite=hs1.iterator(); 
    System.out.println(ite.hasNext());

    if(hs1.size()==0)
    {
     hs1.add(new Student(id, name, marks));
     System.out.println("data entered");
     return;
    }
    while(ite.hasNext())
    {

    Student st1=(Student)ite.next();
    if(st1.id==id)
    {
        System.out.println("duplicte");
    }
    else
    {
        hs1.add(new Student(id, name,marks));
    }



}
    }
public static void main(String[] args) {
    // TODO Auto-generated method stub


    hs1=new HashSet();

    addstudent(1, "naca", 40);
    addstudent(2, "cjlnca", 20);
    addstudent(3, "sdv", 20);
    addstudent(4, "sdv", 20);


    }
}

1 个答案:

答案 0 :(得分:0)

迭代时无法修改任何集合。并且您通过代码

一次又一次地添加条目
{
    hs1.add(new Student(id, name,marks));
}

重复

HashSet通过定义来存储唯一值。

哈希集的粗略逻辑:

在添加之前,hashset调用即将添加的equals方法学生与其他添加的学生检查任何内容是否相同,如果相同则不会添加,否则不添加。

你不需要做任何特别的事情,只需在学生中覆盖equals

public booleqn equals(Object obj) {
 Student other = (Student ) obj;
 return this.id.equals (other.id);
}

请注意,您可能还需要覆盖哈希码