0

Okay, I am saving files in a json file which which unlike a db that has an auto-increment function.

Say I have this object.

public book() {
id = ?????
Title = mTitle;
}

How can you make the id to give you an unique int number? is that possible? Thanks in advance.

tipsywacky
  • 3,374
  • 5
  • 43
  • 75

3 Answers3

3

Have a static variable in the class and increment it.

class Book {

 private static int increment = 0;
 public Book() {
   id = ++increment;
   Title = mTitle;
 }

}

Please follow some naming conventions. Class names should start with uppercase.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • Unless you have a need to know the next id outside the class, increment should be private. – Gabe Sechan Jun 09 '13 at 07:43
  • 2
    suppose the app is restarted the values will be initialized to zero again right? – Raghunandan Jun 09 '13 at 07:47
  • 1
    suppose the app is restarted then even the objects he created with unique ids will not exist . If the requirement is such then he needs to persist the last id somewhere . My answer was in context till app is up in the JVM , not for consecutive running of the app. – AllTooSir Jun 09 '13 at 08:10
2

You have several solutions.

1 Put to your ID System.currentTimeMillis() or even System.nonoTime(). This will almost guarantee uniqueness and the numbers will be consequent.

2 Create static counter that just counts the objects:

example:

public class Book {
   private static int count = 0;
   private int id;

   public Book() {
       id = ++count;
   }
}

This approach will guarantee the uniqueness of IDs within the same instance of your application.

3 You can also use class UUID that generates truly unique string IDs.

AlexR
  • 114,158
  • 16
  • 130
  • 208
1

If you auto-generate your getters/setters, be sure to mark setId() as protected and remove the argument passed in.

public protected void setId() {}
Brian
  • 5,069
  • 7
  • 37
  • 47