GeekOfAUT
GeekOfAUT

Reputation: 19

how to insure a certain field in a class has different and unique values in all instances in java?

I'm new to coding and I've faced this problem recently: I'm working on a class which has various fields, and I want to insure each instance of the class has a unique value for a certain field using static variables. for example, consider this class:

public class NetworkNode  {
private String NodeName;
private int NodeNumber;
private boolean NodeAttraction;
....
}

in the code above, I want to insure each object created from the class NetworkNode to have a unique and different NodeNumber or in other words, no two NetworkNode objects should have the same NodeNumber field. what are the ways to do this? thanks.

Upvotes: 2

Views: 935

Answers (3)

Poohl
Poohl

Reputation: 1924

You could automatically assign a different NodeNumber to each instance if you don't care about the actual value as long as it's unique. Using static variables you could create a private static counter nextNodeNumber in your class NetworkNode:

private static int nextNodeNumber = 0;

In your constructor you could then do

public NetworkNode() {
    this.NodeNumber = nextNodeNumber;
    ++nextNodeNumber;
    ...
}

This way you just have to ensure, that there is no other way to set/change NodeNumber or nextNodeNumber.

If you are using multiple Threads you would have to secure access to nextNodeNumber to prevent asynchronous access.

Upvotes: 1

ChanceVI
ChanceVI

Reputation: 220

I recommend you to do some reading about variables and what static means. To make it short, a static variable exists only "once" in your program.

For example, if you create a game, you want the variable score to be static since there will only be one instance of this variable.

In order to have each NetworkNode to have a unique and different NodeNumber, you have to construct the object like this:

public NetworkNode(String NodeName, int NodeNumber, boolean NodeAttraction){

  this.NodeName = NodeName; 
  this.NodeNumber = NodeNumber; 
  this.NodeAttraction = NodeAttraction; 

}

See, here, each NetworkNode will have a different value for each of the variables passed as parameters.

You will then just need to create the object in your main function or whatever like this for example:

NetworkNode myNode = new NetworkNode("node1", 0, true); 

Hope it helps,

Upvotes: 0

1 put a

static Set<String> myuniquevalues ... (for example) for each of your fields

2 in your constructor

public NetworkNode  (String value1 ...) 
{... check if value1  exists in myuniquevalues , and throw exceptions }

3 if your objects are deleted, you must manage it also ...

Alternative: concentrate creation of your objects in a factory, and manage unicity there.

Upvotes: 0

Related Questions