Java 使用实例方法而不是类/静态方法为每个实例化对象创建唯一 ID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35461651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:41:54  来源:igfitidea点击:

Java create a unique ID for each instantiated object using instance methods instead of class/static methods

javastaticincrementuniqueidentifierinstance-methods

提问by SeesSound

Quite new to this so I hope I have the terminology in the title right.

对此很陌生,所以我希望我在标题中有正确的术语。

I am trying to figure out how to create an instance methodthat will do the following:

我想弄清楚如何创建一个实例方法,它将执行以下操作:

--An ID number is returned.

--返回ID号。

--As each object is created from the class constructor(instantiated?), a unique integer ID number is assigned to it. The first ID number is 1, and as new objects are instantiated, successive numbers will be assigned.

-- 因为每个对象都是从类构造函数(实例化?)创建的,所以会为其分配一个唯一的整数 ID 号。第一个 ID 号是 1,随着新对象的实例化,将分配连续的编号。

I am able to find examples of class/static methods that do the above however I am unable to figure out how to do this with an instance method. My attempt is below:

我能够找到执行上述操作的类/静态方法的示例,但是我无法弄清楚如何使用实例方法来做到这一点。我的尝试如下:

class Coordinates
{
    private int iD = 0;
    private float xCoordinate;
    private float yCoordinate;

    public Coordinates()
    {
        //Asks for input and assigns it to the two variables below
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter the X Coordinate followed by the return key");
        xCoordinate = keyboard.nextDouble();
        System.out.println("Please enter the Y Coordinate followed by the return key");
        yCoordinate = keyboard.nextDouble();

        iD++;
    }

    public getiD()
    {
        return iD;
    }

}

My main method is as follows:

我的主要方法如下:

public class Machine
{
    public static void main(String[] args)
    {
        Coordinates c1 = new Coordiantes();
        Coordinates c2 = new Coordiantes();
        Coordinates c3 = new Coordiantes();

        System.out.println("ID: " + c1.getID());
        System.out.println("ID: " + c2.getID());
        System.out.println("ID: " + c3.getID());


    }
}

Please note I have not included my entire code for the sake of simplicity and easiness to follow. I hope I have added enough.

请注意,为了简单和易于遵循,我没有包含我的全部代码。我希望我已经添加了足够的内容。

I also don't want to use java.util.UUID.

我也不想使用 java.util.UUID。

采纳答案by CoderBC

The problem right now is that your 'id' is an instance variable, meaning it belong to the objects you create. Think of it that every time you create an object a new and fresh copy of your instance variable is made. So every time you create an object the id is first set to 0, then post incremented once (thus all objects have an id=0).

现在的问题是您的“id”是一个实例变量,这意味着它属于您创建的对象。想象一下,每次创建一个对象时,都会创建一个新的实例变量副本。因此,每次创建对象时,id 首先设置为 0,然后 post 递增一次(因此所有对象的 id=0)。

If you want to create a variable that, say, automatically counts all objects you have created in a class or has the id, you need to make a class variable. These variable belong to all the objects you create from a class and the keyword used for that is 'static'.

如果您想创建一个变量,例如,自动计算您在类中创建的所有对象或具有 id 的所有对象,您需要创建一个类变量。这些变量属于您从类创建的所有对象,并且用于该类的关键字是“静态”。

Note: I have used a static variable BUT not a static method. If you don't want to use static at all, it is a different question

注意:我使用了静态变量,但不是静态方法。如果您根本不想使用静态,那是另一个问题

class Coordinates
{
private static int count = 0;
private int id=0;
private float xCoordinate;
private float yCoordinate;

public Coordinates()
{
    //Asks for input and assigns it to the two variables below
    Scanner keyboard = new Scanner(System.in);
    System.out.println("Please enter the X Coordinate followed by the return key");
    xCoordinate = keyboard.nextDouble();
    System.out.println("Please enter the Y Coordinate followed by the return key");
    yCoordinate = keyboard.nextDouble();

    id=count++;
}

public getiD()
{
    return iD;
}

}

A simple change of keyword will make your program correct. You dont have to do too much complicated stuff.

关键字的简单更改将使您的程序正确。你不必做太多复杂的事情。

It is difficult to grasp the concept of class and objects, static and instance variables at first. Let me know if you'd like more explanation :)

一开始很难掌握类和对象、静态和实例变量的概念。如果您需要更多解释,请告诉我:)

回答by pegas

You can either make that ID static, or you could just make a Parent class called "Coordinate" (with that ID again being static) with "Point" children, and increment the ID in the constructor of each "Point" object.

您可以将该 ID 设为静态,或者您可以使用“Point”子代创建一个名为“Coordinate”的父类(该 ID 再次是静态的),并在每个“Point”对象的构造函数中增加 ID。

Static would seem like the way to go.

静态似乎是要走的路。

回答by Nathan Hughes

Maintaining an ID sequence is a separate responsibility from the rest of what your object does, and doesn't belong to any one instance of the Coordinates class, so it belongs in a different object. Make a separate object to maintain the sequence and hand out numbers, something like

维护 ID 序列是与对象所做的其余部分不同的职责,并且不属于 Coordinates 类的任何一个实例,因此它属于不同的对象。制作一个单独的对象来维护序列并分发数字,例如

public class MySequence {
    private AtomicLong currentValue = new AtomicLong(0L);
    public long getNextValue() {
        return currentValue.getAndIncrement();
    }
}

then use that sequence to initialize your objects:

然后使用该序列来初始化您的对象:

new CoordinatePair(mySequence.getNextValue(), x, y);

By the way keeping user input separate from the model makes things simpler, you may want to instantiate your Coordinates class in cases where the input doesn't come from the user. Console input doesn't go in a constructor. You might have a Coordinate class like

顺便说一下,将用户输入与模型分开会使事情变得更简单,您可能希望在输入不是来自用户的情况下实例化 Coordinates 类。控制台输入不会进入构造函数。你可能有一个坐标类

public CoordinatePoint {
    private long id;
    private float x;
    private float y;
    public CoordinatePoint(long id, float x, float y) {
        this.id = id;
        this.x = x;
        this.y = y;
    }
    public String toString() {
        return "id=" + id + ", (" + x + ", " + y + ")";
    }
}

and a main method like

和一个主要的方法,比如

public class Example {

    public static void main(String ... args) {
        MySequence seq = new MySequence();
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Please enter the X Coordinate followed by the return key");
        float xCoordinate = keyboard.nextDouble();
        System.out.println("Please enter the Y Coordinate followed by the return key");
        float yCoordinate = keyboard.nextDouble();
        CoordinatePoint c1 = new CoordinatePoint(seq.getNextValue(), xCoordinate, yCoordinate);
        System.out.println(c1.toString());
    }
}

回答by Alan Hay

In the context of your current code, the simplest thing to to do is as below:

在您当前代码的上下文中,最简单的事情如下:

import java.util.concurrent.atomic.AtomicInteger;

public class Coordinates {

    //static id generator shared among all instances of Coordinates 
    private static final AtomicInteger idGenerator = new AtomicInteger(1000);

    private final Integer id;

    public Coordinates() {
        //assign unique id to an instance variable
        id = idGenerator.getAndIncrement();
    }

    public int getId() {
        //return instance variable
        return id;
    }
}

Test

测试

public class Test {

    public static void main(String[] args) {
        for(int i = 0; i < 10; ++ i){
            System.out.println(new CoordinatePoint().getId());
        }
    }
}

Output

输出

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009

1000 1001 1002 1003 1004 1005 1006 1007 1008 1009