How can I make sure that each instance of a class will have a unique value for a specific parameter?
For example:
public Foo(int value);
value should be different for each instance of Foo. Otherwise, it can throw an exception.
Do you want to assign that value, or do you just want to make sure you have some kind of id?
A minimal solution for an id would be to use a static field as counter:
public class Foo {
private static int counter = 1;
private int id;
public Foo() {
id = counter++;
}
}
To check for assigned values you might want to use some kind of FooFactory:
public class FooFactory {
private static Set<int> ids = new Set<int>();
public static Foo createFoo(int value) {
if (ids.contains(value)) {
throw new FooAlreadyExistsException();
}
ids.add(value);
return new Foo(value);
}
}
Or, as other comments suggest, you could do this in the Foo constructor:
public class Foo {
private static Set<int> ids = new Set<int>();
public Foo(int value) {
if (ids.contains(value)) {
throw new FooAlreadyExistsException();
}
ids.add(value);
}
}
Create a factory:
public Foo createFoo( int value ) {....}
In the factory code, you can maintain a set of "allocated" values. This allows you to optimize the code; for example if the values are consecutive, a BitSet might be better than Set<Integer>. Note that you must "deallocate" your instances of Foo somehow if you want to be able to reuse values.
If you just GC instances of Foo, the value will still be "in use" unless you notify the factory somehow.
Assuming all instances of Foo would be in memory, you can maintain a static Set in the Foo class that would hold the values that were already used. You can check against this Set any time a new instance is created.
Another alternative, assuming there is no functional meaning to this value, is to have some sequence (backed by either a DB or a file) that would increment any time a new instance is created, and the value of each new instance would be the current value of that sequence.
I think your unique value should not be a parameter (which is under control of an arbitrary caller) but a responsibility of Foo.
A simple solution would be to use a static field which is incremented each time an instance is created:
private static int instanceCounter;
// instance initializer
{
instanceCounter++;
}
As others have mentioned this smells of a problem in your design or your understanding of the requirements.
Please share the requirements, your intended design and the code you have created so far.
EDIT: 'Aaron Digulla' has a better suggestion, to create a factory which manages this aspect of the object lifecycle.
I'd propose having a static ArrayList inside of a class, containing a list of your objects. But this is bad design IMHO.
Related
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.
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.
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.
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,
I was wondering what the difference is between
public final type attribute_name;
and
private type attribute_name;
public type getA_name() {
return attribute_name;
}
Basically I want to make an attribute read-only, so it can't change after it has been initialized.
Do I make it public final, or do I make it private, and only make it accesible through a get method (without a set method)?
When it's not final but private, the class itself is able to change the value.
A final field MUST be set before the constructor exits. Once set, the reference cannot be modified (the value cannot be reassigned). Emphasis on the cannot be reassigned. This means that while the reference cannot change, the value itself can change.
This is legal:
final List<Integer> list = new List<Integer>();
list.add(5); // the value of list changes, but the reference doesn't
This is not:
final List<Integer> list = new List<Integer>();
list = new List<Integer>(); // may seem sort of redundant but the compiler won't allow it nonetheless
A private variable with a only getter can be reassigned internally by the class that holds it (but it's not visible externally so it cannot be reassigned outside the class holding it). Also, outside the class the reference is inaccessible so the variable cannot be modified except by the class holding it.
A final variable cannot be reassigned anywhere, but if it's public, another class can still access the reference and change the value of whatever object it points to.
If you don't want the variable to be reassigned after initialization as you described, use both final and private.
Use final for something like this:
public class User {
private final long registrationTimeMillis;
public User(/* various parameters probably would be here */) {
registrationTimeMillis = System.currentTimeMillis();
}
public long getRegistrationTimeMillis() {
return registrationTimeMillis;
}
}
We don't expect that a user's registration time will change, so it makes sense to not allow it to change after construction.
Use private with no setter for something like this:
public class VendingController() {
private int drinksStocked = 0;
private int drinksDispensed = 0;
public void dispenseDrink() {
drinksDispensed++;
}
public void stockDrinks(int numberOfDrinks) {
drinksStocked = getDrinksRemaining() + numberOfDrinks;
drinksDispensed = 0;
}
public int getDrinksRemaining() {
return drinksStocked - drinksDispensed;
}
}
We don't want the value of drinksDispensed to change except when dispenseDrink() or stockDrinks(int numberOfDrinks) is called. It still needs to be able to be reassigned by it's own class when the vending machine is refilled though, so we shouldn't make it final
With respect to using public final, generally in Java that's only done for constants and that static keyword is also included since constants shouldn't be dependent on an instance.
An example of when it makes sense to use public static final
public class UnitConversions {
public static final double CENTIMETERS_PER_INCH = 2.54;
}
It could then be used in a method as follows
public double convertFromCentimetersToInches(double centimeters) {
return centimeters / UnitConversions.CENTIMETERS_PER_INCH;
}
Best of luck OP and happy coding.
More reading on final fields
This depends on some factors.
If this is a real constant that is known before and will never change, then use final. In Java final fields can be initialized in the constructor as well, so if your value is known at construction time then you can use final too.
If this value gets set (once, multiple times) during runtime then use private + getter.
The final modifier allows a field to be assigned only once - it cannot be changed after that and it has to be set at during object construction (that is, before the constructor returns).
If you want to make the field read-only, use the principles of information hiding: make it private and provide a public getter that returns the field (or a copy of it for non-primitive types).
You should use public final only for true constants. Even if your field is immutable because of final it is often a good idea to still make it private.
The correct way is to think in the future. What would help you achieve your goals? Maybe later you would also like to give that variable a value. If I were you, I'd do this by creatin a get method and keeping the variable private.
Full documentation for final keyword : http://en.wikipedia.org/wiki/Final_(Java)
Depends on where you want to access it from. Public variables can be accessed from any class within the project and package where private can only be accessed from the class where the variable is.
The 'final' operator makes it permanent and read-only.
Let's assume that type is a reference to an object, not a primitive type.
public final type attribute_name means that attribute_name cannot be reassigned to refer to something else. But attribute_name can be used to call a method that changes its state.
In private type attribute_name, only methods within the class can call methods on attribute_name.
So if you want it to remain constant, use approach (2). Limit the public methods to ones that ultimately call methods on attribute_name that don't modify its state.
I'm encountering a couple awkward situations that seem, in some sense, dual to each other, and was wondering if anyone had any thoughts about how to handle them cleanly.
External initialization
class Human {
Collection <Human> nextDoorNeighbors;
}
class Neighborhood {
Collection <Human> humans;
Neighborhood() {
// Make humans
// Then, let them all know who their neighbors are.
}
}
This is awkward because the humans (in this situation) never have to change their next-door neighbors once they've been set up (they are effectively write-once), but this setup can't be done in the Human constructor because the neighbors that need to be put in the nextDoorNeighbors collection don't all exist when the human is constructed.
Holding something for another
Suppose I want to be able to store Humans in a tree-based map. To do so, the Human has to hold a Comparable ID, even if that isn't logically significant to the concept of a Human. The Human constructs this ID, but it never uses it. Only the map uses it (or even should use it).
In the first case, maybe the awkwardness is an indication that neighbours shouldn't be a property of Human. Perhaps the Neighbourhood object should be a property of Human, and a method like human.getNeighbours() can be used to get the actual neighbours when they are needed. Then having a neighbours property becomes a private performance issue for the getNeighbours() method.
In the second case, how is your tree-based map providing a structure if the Human is inherently unstructurable? What's the map for if the ID is irrelevant to the human? Typically an ID is relevant, and is used by the class that has it to ensure that it's uniquely identifiable, but if it's genuinely not required, you can use a separate class, like a HumanKey, to wrap the Human for the map.
I don't really understant what your question is.. Because it's not explicit..
But for the id you can have a static variable in the human class that you will increment in the human constructor and another variable wich will contain the id
It would be something like this
class Human
{
private static int humansCounter=0;
final public int id;
public Human()
{
id=humansCounter++;
}
}
I have an approach that I think is rather clean if the objects themselves need to be aware of the networking. Note that this approach will not work if you concurrently instantiate instances (since each thread will have its own copy of the static fields).
class Foo {
// instance fields
public Foo(/* constructor args */) {
// set instance up
network(this);
}
public boolean isNeighbor(Foo that) {
return areNeighbors(this, that);
}
// static field for tracking edges between neighbors, maybe a
private static Map<Foo, List<Foo>> neighborhood = new HashMap<>();
private static void network(Foo me) {
myNeighbors = new ArrayList<>();
for (Map.Entry<Foo, List<Foo>> x : neighborhood.entrySet()) {
Foo n = x.getKey();
if (/* use me and n's fields to determine whether they are neighbors */) {
myNeighbors.add(n);
x.getValue().add(me);
}
}
neighborhood.put(me, myNeighbors);
}
public static boolean areNeighbors(Foo a, Foo b) {
return neighborhood.get(a).contains(b);
}
}
This approach makes it so that each instance can determine their neighbors without actually knowing their neighbors ahead of time and without using an external class. If an instance's neighbors cannot be inferred from internal state, this approach could be combined with the approach of generating unique IDs (hashes?) for each instance:
class Bar {
// instance fields
public Bar(/* constructor args */, int... neighborIndices) {
// set instance up
network(this, neighborIndices);
}
#Override
public int hashCode() {
return /* a unique value based upon this object's state */;
}
public boolean isNeighbor(Bar that) {
return areNeighbors(this, that);
}
private static Map<Integer, Bar> lookup = new HashMap<>();
private static Map<Bar, List<Integer>> neighbors = new HashMap<>();
private static void network(Bar me, int[] neighbors) {
lookup.put(me.hashCode(), me);
List<Integer> neighborList = new ArrayList<>();
for (int i : neighbors) {
neighborList.add(i);
}
neighbors.put(me, neighborList);
}
public static boolean areNeighbors(Bar a, Bar b) {
return neighbors.get(a).contains(b.hashCode());
}
}
Naturally, if the neighbor relationships are not associative, it is trivial to modify the first example to be a digraph.
I have been working to upgrade my Java code baseline so that it follows good security practices and have run into an issue related to generics. Say you have the following:
public class SomeClass<T>
{
private T value;
public T getValue()
{
return value;
}
public void setValue(T value)
{
this.value = value;
}
}
I have not found a good answer on how to edit these methods so that value does not leak like it does in this example class for a generic object that does not implement Clonable and in some cases has no default constructor.
As I understand it, you want to make sure that nothing outside SomeClass can mutate the object value.
In C++, you could returns a const reference (avoid copying altogether), but Java does not have that. So let's look at copying...
First, know that some objects cannot be copied. For example, stream, gui elements, etc. Thus, trying to copy all objects is a hopeless endeavor from the start.
But what about objects that are copiable?
In Java, you cannot call the copy constructor (or any other constructor) of a generic (Calling constructor of a generic type).
There is the Cloneable interface, but that is really nothing more than a promise that clone works; it does not actually expose clone publically. Thus, for generics, you have to use reflection, as shown here.
Unfortunately, there is no good solution. The only viable one (except for changing the purpose or semantics of your class) is to use the clone method as shown in the link above, and realize that some objects cannot be copied.
Ultimately, the best thing to do is find a solution that does not require this. Make a (non-generic) read-only wrapper class that exposes the non-mutating methods. Or stipulate in documentation that mutating methods must not be called.
I can see three approaches:
Make copies. This of course would only work with types can can be copied (and that you know how to copy).
Only support immutable types.
Remove getValue(). Instead, provide methods that operate directly on this.value without exposing it outside the class. In this approach, setValue() can still be problematic (you need to make sure that the caller does not hold on to the object reference after calling setValue()).
If T can be arbitrary type that you have no control over, then options 1 and 2 won't be suitable.
I believe that i undestand you ... If you want to restrict a generic type you should use extends keyword that in generic type is not equals to general class. If you use only the class how implements Clonable are able to instantiate this class. One example:
public class Stack {
public static void main(String[] args) {
SomeClass<Animal> sc = new SomeClass<>(); //This generate an error because doesnt implements Clonable interface
SomeClass<Person> sc1 = new SomeClass<>();
}
}
class SomeClass<T extends Comparable> //Note that extends means implements or the common extends
{
private T value;
public T getValue()
{
return value;
}
public void setValue(T value)
{
this.value = value;
}
}
class Person implements Comparable<Person>{
#Override
public int compareTo(Person p){
return 0;
}
}
class Animal {
}
I wish i helped you.
:)
An object whose state is encapsulated in a mutable object should generally never expose to the outside world any reference to that object, and should avoid giving the outside world a reference to any mutable object (even a copy) which claims to encapsulate its state. The problem is that given code:
Foo foo = myEntity1.getFoo();
foo.bar = 23;
myEntity2.setFoo(foo);
foo.bar = 47;
myEntity3.setFoo(foo);
there is no clear indication whether or how the change to foo.bar would affect the various entities. If the code had instead been:
Foo foo = myEntity1.getFoo();
foo = foo.withBar(23); // makes a new instance which is like foo, but where bar==23
myEntity2.setFoo(foo);
foo = foo.withBar(47); // makes a new instance which is like foo, but where bar==47
myEntity3.setFoo(foo);
it would be very clear that the bar property of myEntity1's foo will be unaffected, that of myEntity2 will be 23, and that of myEntity3 will be 47. If foo is a mutable class, the pattern should be:
Foo foo = new Foo();
myEntity1.writeTo(foo); // Copy properties from myEntity1 to the supplied instance
foo.bar = 23;
myEntity2.readFrom(foo); // Copy properties from the supplied instance to myEntity2
foo.bar = 47;
myEntity2.readFrom(foo); // Copy properties from the supplied instance to myEntity3
Here, myEntity1 isn't giving the caller an object, but is instead copying data to an object supplied by the caller. Consequently, it's much clearer that the caller shouldn't expect the writes to foo.bar to affect the entities directly, but merely change what will be written in subsequent readFrom calls.
Basic question from somebody coming from structured into object programming... hoping not to be too basic.
I want to have a large array of data that is been shared by different classes inside my application.
What's the best practice to do this?
Is this correct?
public class LargeData {
private static long[] myData;
private static final int MAX = 100000;
public LargeData() {
myData = new long[MAX];
// ... initialize
}
public long getData(int x) {
// ... do whatever and return a long
}
}
And if this is correct, how is the correct way to access this data from any of my classes? Should I make a
LargeData ld = new LargeData();
inside every single class that wants to access to myData?
Thank you and sorry for being too easy... :)
use a Singleton pattern for this.
Everytime you call
LargeData ld = new LargeData();
in your code, you will be effectively calling
myData = new long[MAX];
which is wrong.
What you can do is:
public class LargeData {
private static final int MAX = 100000;
public static long[] myData = new long[MAX];
}
and access it as LargeData.myData from anywhere.
initialize array immediately. with current implementation you won't be able to use static array until create object of LargeData.
Also if class just for holding array prevent its instantiation and extension by making it final and constructor as private.
public final class LargeData {
public static long[] myData = new long[100000];
private LargeData() { }
}
And get access as LargeData.myData
Assigning values to static variables from instance constructors is a bad idea without a null check - if you ever instantiate two objects from this class the second will cause you to lose all data stored in the array (you lose the reference to the old array when the second instantiation overwrites the static reference). With null check it is also a bad idea though, unless you really really really need the data in one instance sort of a "global variable" way. It is best to think of static references as global variables which can be either viewable by all (if they are public) or visible only from the class you define it in (private) or something in between (protected or package protected access). You pretty much want to avoid using them though in almost all cases and use the Singleton pattern instead of static variables inside classes. With the Singleton pattern you use instance variables and non-static getters to get to the data.
However I do not see given the things you wrote why you would need a singleton pattern for this particular problem - you just want to store data in an object and share that object around, right?
You can fix the posted code like this without static keywords and this allows multiple LargeData instances to be alive at once in your application:
public class LargeData {
private long[] myData; // instance variable to store the data
private static final int MAX = 100000; // max length
public LargeData() {
myData = new long[MAX];
}
public long[] getData() {
return myData;
}
}
Then you can use the data as:
LargeData ld = new LargeData();
long[] = ld.getData();
And you can use the reference stored in ld any way you like, you can pass it around your other classes, etc.
A better idea would be to not expose the array, rather create an API through which you use the stored data. For example:
public long getLong(int n) { return myData[n]; }
public void setLong(int n, long value) { myData[n] = value; }
Now if you don't want to pass around the reference to the LargeData instance stored in ld, you can use a static variable in LargeData to store the reference and a static getter which lets you access it from any other java code. If you need multiple LargeData instances to work with you can create a LargeDataRegistry class that encapsulate a Map where you would store each instantiated LargeData instance.