Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create unique IDs to my objects

Tags:

java

I have basic knowledge of java and I want to create unique ids for my employees , but I also don't want to use java.util.UUID . How can I do that ? and where and what method should I add to my code ? Thank you

import java.util.ArrayList;

public class Main {

    private static ArrayList<Employees> list = new ArrayList<>();

    public static void main(String[] args) {
        Employees emp =new Employees(15, "xx", 23);
        Main.add(emp);        
    }

    public static void delete(int id) {
        list.remove(get(id));
    }

    public static void updateName(int id, String name) {
        get(id).name=name;
    }

    public static void updateAge(int id, int age) {
        get(id).age=age;
    }

    public static Employees get(int id) {
        for(Employees emp : list)
            if(emp.id==id)
                return emp;
        throw new RuntimeException("Employees with id : "+id+" not found");
    }

}
class Employees {

    String name;
    int age;
    int id ;

    public Employees(int id, String name, int age) {
        //super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

   @Override
    public String toString() {

        return id+" : "+" "+name+", "+age+" ans";
    }
}
like image 624
M.Maria Avatar asked Jan 18 '26 10:01

M.Maria


1 Answers

You can have a static variable, which will be used to have an id, and after assignment it will be incremented, to assure that the next one will be different :

class Employees {

    String name;
    int age;
    int id ;
    static int counter = 0;

    public Employees(String name, int age) {
        this.id = counter++;
        this.name = name;
        this.age = age;
    }
  }

So you can remove the int id in the constructor


Also :

  • Main.add(emp) is wrong and may be replaced by list.add(emp)
  • updateName and updateAge may use setters defined in Employees to follow conventions (and better separate classes, and set attribute visibility to private)
like image 58
azro Avatar answered Jan 21 '26 03:01

azro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!