java—如何为没有参数的对象设置值

yb3bgrhw  于 2021-07-12  发布在  Java
关注(0)|答案(2)|浏览(238)

我是java编程的初学者,我想重写下面的代码,但是为了自己设置id号,我希望id号自动设置为$1,2,3,…$我知道我必须使用id作为静态变量,我应该在构造函数中用id++递增。问题是我不知道如何自动生成。我希望每个学生都有自己的id,因此当我编写例如robert.getid()时,它会给我他的id,但我不希望id是一个参数,那么我的对象构造将是:

Students robert = new Students("Robert Smith", 8, 3500);

所以我只需要提供姓名、年级和学费,id自动设置为robert object,我怎么做?

package schoolManagementSystem;

public class Students 
{
    //Instance Variables

    private int id,grade, tuition;
    private String name;

    //Constructors

    /**
     * constructs an object of the class Student
     * @param id id of the student
     * @param name name of the student
     * @param grade grade of the student
     * @param tuition tuition the student has to pay
     */
    public Students(int id,String name, int grade,int tuition)
    {
        this.id = id;
        this.name = name;
        this.grade = grade;
        this.tuition = tuition;
    }
public int getId()
{
    return id;
}
}
bq8i3lrv

bq8i3lrv1#

这应该管用。让我知道

import java.util.*;

public class Students
{
    //Instance Variables

    private int id,grade, tuition;
    private String name;

    private static Set<Integer> idSet = new HashSet<>();
    private static Map<Integer, Students> db = new HashMap<>();

    //Constructors
    /**
     * constructs an object of the class Student
     * @param name name of the student
     * @param grade grade of the student
     * @param tuition tuition the student has to pay
     */
    public Students(String name, int grade,int tuition)
    {
        this.name = name;
        this.grade = grade;
        this.tuition = tuition;
    }

    public int getId() {
        if (idSet.contains(0)) {
            int max = Collections.max(idSet);
            int newMax = max + 1;
            db.put(newMax, this);
            idSet.add(newMax);
            return newMax;
        } else {
            int max = 0;
            db.put(max, this);
            idSet.add(max);
            return max;
        }
    }
}
s4n0splo

s4n0splo2#

使用atomicinteger和getandincrement()方法,您的程序将如下所示

public class Students 
{
    //Instance Variables
    private  AtomicInteger count = new AtomicInteger();
    private int id,grade, tuition;
    private String name;

    //Constructors

    /**
     * constructs an object of the class Student
     * @param id id of the student
     * @param name name of the student
     * @param grade grade of the student
     * @param tuition tuition the student has to pay
     */
    public Students(int id,String name, int grade,int tuition)
    {
        this.id = id;
        this.name = name;
        this.grade = grade;
        this.tuition = tuition;
    }
public int getId()
{
    return  count.getAndIncrement();

}
}

相关问题