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

Best way to convert this String to int
Ant build dex no response
As I can generate automatic notifications
Unkwon object in a file while writing from arraylist object
Why do I get the “number stored as text” error on a few values?
JFrame not refreshing on repaint
Which is better way of having a null check?
How to convert String to BigDecimal without scientific notation
Vaadin - serializable errors on Tomcat
I am having error to display the image file save in memory in android,
Getting the next leafnode in a binary search tree using an iterator
Dumping a huge array in Intellij-Idea debugger
Reset JDBC connections of Connection Pool in Java
How to automatically export project in eclipse?
Input Listener Java [Android Studio]
Reverse String Array w/Method

Categories

HOME
client
bluetooth
blogger
netbeans
smarty
relative-path
alpha
ezpublish
esper
slurm
spring-kafka
etl
windows-azure-storage
usergrid
hex-editors
visual-studio-cordova
designer
visual-composer
lldb
dbext
jtextfield
swiftlint
physics-engine
excel-2007
vlsi
tdd
bootstrap-duallistbox
maxmind
spring-mybatis
procdump
sql-server-2012-express
semantic-versioning
exuberant-ctags
contact-form
calibre
framemaker
avcapturesession
geopositioning
cookiecutter-django
email-templates
ruby-on-rails-3.1
powershell-dsc
gpx
wptoolkit
auto-update
fault
revapi
atomicity
gabor-filter
jxcore
media-player
mediaelement
nxt
thrust
packagist
fadeout
nessus
freedesktop.org
retina
django-unittest
quicklisp
ionic
arcanist
notify
kineticjs
gulp-less
internet-connection
html-helper
zend-route
google-reader
expected-exception
undefined-reference
srs
prettify
dexterity
spring-io
blending
dataadapter
android-screen-support
comaddin
ember-app-kit
flashvars
http-unit
kyotocabinet
funscript
enter
work-stealing
horizontal-accordion
netbeans-7.1
ecl
krl
android-sdk-2.1
google-friend-connect
dentrix
multi-tier
sustainable-pace
spec#
scripting-languages
post-build

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App