我正在寻找一种方法来为java中的对象创建不可更改的ID。我认为这是非常基本的东西,但我是初学者。
如果这是我的代码:
public class Node implements IXYNode
{
String id ="";
String description ="";
int x =0;
int y =0;
public XYNode(String id, int x, int y)
{
this.id=id;
this.x=x;
this.y=y;
if(this.id.equals(null) || this.id.isEmpty())
{
throw new IllegalArgumentException();
}
}
}
所以一旦给出,之后就不能更改,提前致谢!
最佳答案
将 id 设置为final
,并且除非它是构造函数或在声明时间,否则不能再次分配它。
final String id ="";
关于java - 创建不可更改的ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35893443/