java


Generate unique int whenever a new object is created


I want to create a class:
class Student {
private static int id;
}
Each time an object from Student is created, it will assign a unique 6 digit ID for that student.
The other related questions I found on Stack Overflow were not that helpful.
You could use a static method that relies on a static int field in the Student class.
If you have race condition in Student constructor invokations :
public class Student {
private static int currentId = 0;
private static final int MAX_VAUE_ACCEPTED = 999999;
private static Object lock = new Object();
private static int getNewId() {
synchronized(lock){
if (currentId > MAX_VAUE_ACCEPTED) {
// handling the problem because you is over 6 digits
}
currentId++;
return currentId;
}
}
...
private int id;
public Student(){
this.id = getNewId();
}
}
If you have not any race conditions, it is the same thing but without the synchronization.
As a side note, if you use a numeric value to store the information, you should do a conversion to a String to render the id if you want to have a representation on 6 digits in all cases.
Because for example 000001 is not a representation that you have naturally from a number. You would have rather : 1.
If you need it, you should have a method that makes the conversion to render the id.
You could define an ID class that has a getID method to return a new 6 digit id every time it's called:
class ID {
private int id = 0;
private final int max;
private final String pattern;
public ID(int digits) {
this.max = (int) Math.pow(10, (digits));
this.pattern = "%0" + digits + "d";
}
public synchronized String getID() {
if(!(id < max)) throw new IllegalStateException("Too many IDs");
return String.format(pattern, id++);
}
}
(Using String here for formatting reasons, you don't need to do calculations with an id any ways.)
Then in your Student class you can simply create a static ID, and call getID whenever you need a new id.
class Student {
private static final ID idFactory = new ID(6);
private final String id = idFactory.getId(); // will always get called for new Student
...
}
However, if a Student object is garbage collected the Id it had will not become available again. You could implement that too, but this will probably be enough in your case.

Related Links

How to split a string in java by a non printable ascii character (Example - Record Seperator) [duplicate]
difference between % (modulus) and / (divided) in java? [duplicate]
Sort List using buttons from Toolbar Menu
Map a domain to custom Url
JTable rows count has default value (4 rows) ONLY
Deleting items from DB using hibernate
Using JTextField and JButton to open an url
how to extends entity class for xml using jaxb and jersey
Quartz's JobDataMap & multiple triggers for single job
Libgdx Particle2D looking weird
Storing game object constants without a giant “Constants” class
Httppost not working - Getting a html response instead of JSON in Android
The application may be doing too much work on its application
javax.persistence.TypedQuery.getSingleResult() NoResultException even though record exist
I am getting java.sql.SQLSyntaxErrorException but i dont seem to mistake sql syntax
How to get P tags found in div tags with selenium webdriver

Categories

HOME
xamarin
ionic-framework
blogger
webpack
angular-material
lodash
fme
cplex
webstorm
react-redux
v8
datastax-java-driver
indesign
qore
node-pdfkit
fancybox-3
moonmail
dtrace
visual-studio-cordova
netflix
telephony
facebook-page
jsdoc
pugjs
lucene.net
alpine
scichart
conemu
sylius
wkwebview
trading
crystal-reports-2010
facet
filezilla
dbclient
vision
bpel
twilio-api
titanium-mobile
android-kernel
wpf-controls
ios5
wixsharp
suricata
libvpx
sharefile
email-templates
quadratic-programming
jvm-languages
node-gyp
nomethoderror
android-mediaprojection
menuitem
parentheses
filepicker
dropbox-php
dotnetzip
darcs
setter
worker-thread
linode
gcsfuse
spring-cache
radtreelist
probability-density
mathematica-frontend
merge-conflict-resolution
phpcas
freedesktop.org
dukescript
processmodel
remobjects
camanjs
qpainter
winddk
websocket4net
html-helper
openexr
seaside
rtmfp
didselectrowatindexpath
centos5
viadeo
farseer
access-rights
opcache
ril
batterylevel
html4
interface-orientation
spring-validator
clipper
selected
pvrtc
sublist
appconkit
mercurial-server
window-management
gnustep
mod-auth
psi
winbugs14
disclosure
jmock
web-application-design
gin
project-hosting
scripting-languages
geneva-server

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App