Reputation: 111
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";
}
}
Upvotes: 3
Views: 4129
Reputation: 833
Hey Try using Random
java class.
import java.util.ArrayList; import java.util.Random;
public class EmpUniqueId {
public static void main(String[] args) {
int empid1 =generateDummySSNNumber();
Employees emp1 = new Employees(empid1 , "xx", 23);
int empid2 =generateDummySSNNumber();
Employees emp2 = new Employees(empid2, "xx", 23);
ArrayList<Employees> list = new ArrayList();
list.add(emp1);
list.add(emp2);
for (Employees object: list) {
System.out.println("Employees id is :-"+object.getId());
}
}
public static int generateDummySSNNumber() {
Random random = new Random();
int min, max;
min = 1;
max = 2000;
int num = random.nextInt(min);
int num1 = random.nextInt(max);
System.out.println("Random Number between given range is " + num1);
return num1;
}
}
class Employees {
String name;
int age;
int id ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = 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";
}
}
Upvotes: 0
Reputation: 54168
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)Upvotes: 6