Integer property as automated generated number - java

I'm creating a simple Java app that would store and display information for customers.
I want to make the id as an automated generated number but having problems with that, don't know should I set it in get or set methods?
Can anyone help me to use that value as?
Here is an example:
public class Customer{
public Person(String firstName, String lastName, String email, String address, String country){
this.id.set(Integer.parseInt(UUID.randomUUID().toString()));
this.firstName.set(firstName);
this.lastName.set(lastName);
this.email.set(email);
this.address.set(address);
this.country.set(country);
}
private final IntegerProperty id = new SimpleIntegerProperty(this,"Id",0);
private final StringProperty firstName = new SimpleStringProperty(this,"First Name","");
private final StringProperty lastName = new SimpleStringProperty(this,"Last Name","");
private final StringProperty email = new SimpleStringProperty(this,"E-mail","");
private final StringProperty address = new SimpleStringProperty(this,"Address","");
private final StringProperty country = new SimpleStringProperty(this,"Country","");
I also created generic bean methods but it's just simple like this:
public StringProperty firstNamePropery(){
return firstName;
}
public String getFirstName(){
return firstName.get();
}
public void setFirstName(String firstName){
this.firstName.set(firstName);
}
//...rest of the methods...
I tried to use this but doesn't work:
public IntegerProperty idProperty(){
return id;
}
public Integer getId(){
return id.get();
}
public void setId(){
this.id.set(Integer.parseInt(UUID.randomUUID().toString()));
}
Thank you for helping me on this one.

A UUID string looks like this 38400000-8cf0-11bd-b23e-10b96e4ef00d. You can't parse this string into an Integer.
If you want to use UUIDs as the Ids for the customers then, declare the attribute as UUID or String instead of Integer.
EDIT I
Also, I don't need to store it as an Integer value, the string can do
job but just can't get to create that number when creating a new
instance of that class.
To use a UUID as a String:
In the Customer class the id attribute must be of type String instead of Integer (or int).
To get a new String representation of the UUID you call UUID.randomUUID().toString(). The result of this call can be assigned to the customer's id without doing any parsing.
Also note that the signatures of the getter and setter have to change accordingly.
In the current setId() method you are creating a new id. This would override the id assigned when the Customer is created using the call in the constructor. If you want flexibility to assign a new id you can have the setId receive a new UUID string and assign that as a new id to the Customer object.
public class Customer{
public Customer(String firstName, String lastName, String email, String address, String country){
this.id.set(UUID.randomUUID().toString());
}
...
public String getId(){
return this.id;
}
public void setId(String newId){
this.id = newId;
}
}
Note: The class name is Customer and the constructor is Person. This is wrong, both must have the same name. You must have some compiler error telling you this. I will assume the correct name of the class and constructor is Customer
/EDIT I
The use case for UUID is when you need to have a unique id without checking if the id already exists with some other party (for example a database engine or a server in a network application without a central server).
If what you want to use is Integer (or Long) there is no real reason to use a Random number, you can use a sequential number for your ids.
If if is a standalone application in javafx, and you are not using different threads to create customers in parallel, then there isn't much more to worry about.
On the other side if it is a client server application. Then you have take in mind the concurrent access of clients to the server.
If you delegate the id creation as a sequence in the database then, the concurrency issue or generating duplication in the id is taken care by the database itself. This could be an autoincrement field in the same customer table (assuming you are using one), a sequence, or a table acting as a sequence. On another side, if it is a class of yours which is going to generate the ids one by one, then you will have to take care of concurrent requests. You will have to make sure that only one thread can increment the id at a time.
Regarding getters and setters, getXxx() returns the value of xxx attribute. and setXxx(123) would set or assign the value 123 to the attribute xxx;

Related

i Have written this membership class, how can i create a method to find a specific ID given to a member?

Guys this is my membership class so far, i am struggling to create a method that finds the full members details that i have given just using a uniqueId finder. Please help.
public class Membership {
private String FirstName;
private String LastName;
private int memberId;
private String listOfMembers;
private int uniqueId;
private long phoneNumber;
public Membership(String FirstName, String LastName, int uniqueId,
long phoneNumber)
{
this.uniqueId = uniqueId;
this.FirstName = FirstName;
this.LastName = LastName;
this.phoneNumber = phoneNumber;
}
public String getMember()
{
return FirstName + LastName;
}
public String getlistOfMembers()
{
return (FirstName + LastName);
}
public int getId()
{
return uniqueId;
}
public void MemberId (int Id)
{
System.out.println("Id" + Id);
}
public String getMemberDetails ()
{
System.out.println("Member Id: " + uniqueId);
System.out.println("first name: " + FirstName);
System.out.println("LastName: " + LastName);
System.out.println("Member phone number: " + phoneNumber);
return listOfMembers;
}
}
This is what i have done so far.
Issues:
You've got user interface code where it doesn't belong. I would remove all System.out.println statements from this class and instead leave it in a UI class or main method (if very simple).
In particular, getter methods should return field values, and should not have System.out.println statements
I'm not sure why this class has a listOfMembers field, or why it's just a String. You look to be trying to combine Member and Membership together in one single class -- Don't do this.
I'd name this class Member since it holds information for just a single Member.
If I needed a Membership class, it would instead hold an ArrayList<Member>
And it would have a public Member getMember(int id) method that would return the item in the list above that shares the id passed into the method. A simple for loop that iterated through the list, comparing id's would suffice.
To add on Hovercraft's answer with an example.
You have your class handling all the members, very basic implementation of it.
public class Membership {
private final Map<Integer, Member> members = new HashMap<>();
public void addMember (Integer uniqueId, Member member) {
members.put (uniqueId, member);
}
public void getMember (Integer uniqueId) {
return members.get (uniqueId);
}
...
}
Then you have the Members themselves like this, more fields can be added as you want them.
public class Member {
private String firstName;
private String lastName;
public Member (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName () {
return firstName;
}
...
}
This is a very basic, but strong, feature in OOP to use.
Again see Hovercraft's answer as it provides all the details. If they were to edit/remove I will update this one.
Map vs List
One minor thing is I'd vote against using an ArrayList<E> to store the Members. If you add to the implementation that you can remove users the uniqueId will shift from user to user. Instead I would be for making sure that you are not adding to an existing user.
If you want to keep it simple and just get going, an ArrayList<E> works, do know the problem you might get in the feature, an uniqueId is not necessarily tied to a Member.
"I am quite new to java and have never come across "map" can you please explain what it is?"
"An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value." - From: Documentation.
Instead of working with direct indexes as you do in an Array:
arr[5]; // here you get the value at index position 5.
Or like a List:
list.get(5); // here you get the fifth element, it can be stored (almost) anywhere in the memory, before or after 4, doesn't matter, as 4 knows where 5 is.
And for a Map:
map.get(5); // you get the object stored at 5, there might not be a 3 or 4 in the Map. You can store any Objects as anything. A String is another example of a common key.
I would suggest to use Map and use id as key of Map and store object of Membership as Value,thereby easy to retrieve and store also.
Something similar to this,
Map<Integer,Membership> map = new HashMap<Integer,Membership>();
Membership m = new Membership("First", "LastName", 1,1234567890);
map.put(m.getId(), m);
To get member by id,
System.out.println(map.get(id).getMemberDetails());

Constructor with many parameters

I have a class with (say) 50 fields. I only use a few of them per deployment of the program per user need. Is there a way to make the constructor generic yet specific to the deployment?
e.g
public class Employee{
private String id = "default";
private String empcat = "default";
private String empfam = "default";
private String phychar = "default";
private String othchar = "default";
private String shoesty = "default";
private Double shoesiz = 0.0;
private String shoesty = "default";
private Double shirsiz = 0.0;
private String shirsty = "default";
.........50 other fields..
}
"User/Customer 1" - only wants to use the program for shoe and thus instantiates the object with :
Employee obemp = new Employee("John", 11.5, Dockers); (i.e. id, shoesiz and shoesty)
User/Customer 2 - only wants to use the program for shirt and thus instantiates the object with :
Employee obemp = new Employee("John", 42, ABC); (i.e. id, shirsiz and shirsty)
User/Customer 3 - only wants to use the program for family and thus instantiates the object with :
Employee obemp = new Employee("John", "Smith"); (i.e. id, empfam)
The order of the fields during the object creation can be different - depending on the usage in the model.
First of all, I'd suggest breaking your main class down into smaller pieces that manage data which typically goes together (Shoe information, Shirt information, Family information, etc.).
Secondly, I'd suggest you provide customers with a builder pattern to make it easy for them to construct an object with just the pieces that they're likely to need. That way, they can do something like this:
Employee emp = new EmployeeBuilder("John")
.withShirtInfo(shirsiz, shirsty)
.build();
There is no generic way in core java to do this. But you may use some design pattern like - builder pattern.
You may also create an Employee with some minimum criteria like - id. We can assume each Employee have an id. So create an Employee with the id using the Employee(String id) constructor -
public class Employee{
//all properties
public Employee(String id){
this.id = id;
}
//setter methods
}
Suppose you have create an Employee like this -
Employee employee = new Employee("eng134");
After that you can set only required property to employee object using the setter methods -
employee.setShoesiz(9);
employee.setShirsiz(26);

Return an int value to Database

I am working on an application which makes it easier for employees to return lost luggage.
I'm working on a screen which registers a piece of luggage.
The status ComboBox is filled with data from the database, as well as the CustomerID combobox.
SCREEN:
http://gyazo.com/d81c7c2377c79eb2b42d6f101fb8d5f5
Now the ComboBox fetches an SQL query, and shows a firstname. But the customer has a customerID as well. For now i have a method which sets the value of the variable customerId, with:
lug.setCustomerID(String.valueOf(CustomerID.getSelectedItem()));
But then it sets its value to 'Khoa'.
How can i show a name in my combobox, but get the INT value of the customerID?
Instead of just adding strings to the ComboBox you can add an object with both ID and String.
You need to override the toString() function of your class from which you create the customer object.
public class Customer {
private String name;
private int id;
public Customer(String label, int identifier) {
name = label;
id = identifier;
}
public getId() { return id; }
#Overrider public String toString() { return name; }
}
You can when using an object out of that class
lug.setCustomerID(CustomerID.getSelectedItem().getId());
You should wrap your data in simple bean (e.g. Customer) with 2 fields: int id; String firstName and toString must return firstName.
After declare your combobox as JComboBox<Customer>.
The result will look like lug.setCustomerID(CustomerID.getSelectedItem().getId());

Adding multiplie objects to an ArrayList in java

I have a class named Customer which stores the following objects:
private String CustomerFirstName
private String CustomerLastName
private String CustomerID
private String CustomerEmail
now in order to pass data to jasper report, I decided to create an array list which contains these objects, so :
import java.util.ArrayList;
import java.util.Collection;
/* This is CustomerDataSource.java file */
public class CustomerDataSource {
public static Collection<Customer> loadCustomers() throws Exception {
Collection<Customer> customers = new ArrayList<Customer>();
Customer customer = new customer (
/* I need help getting the objects CustomerFirstName / CustomerLastName and etc */
);
customer.addBilling(new Billing ( /* Adding billing info */ ));
customer.getBilling(new Billing ( /* I need to get the object's values*/));
customer.balOwing();
customers.add (customer);
return customers;
}
}
can someone please explain how to add the objects in Customer.java to the array list? (and in general since I need to add objects from different files as well. Thank you
So as I see your problem in your comment, you want to create a constructor.
In your Costumer class
public Costumer(String firstName, String lastName, String ID, String email) {
this.CostumerFirstName = firstName;
this.CostumerLastName = lastName;
this.CostumerID = ID;
this.CostumerEmail = email;
}
So then you can create a new costumer like that:
Customer customer = new Customer ("SampleFirstName","SampleLastName","0000","address#web.com");
You could even add the costumer automatically to the ArrayList by adding it in the constructor.
From your comment, I am guessing you would like to use a constructor?
You will have to add a constructor on your Customer.java.
public Customer(String firstName, String lastName, String id, String email){
this.CustomerFirstName = firstName;
this.CustomerLastName = lastName;
this.CustomerID = id;
this.CustomerEmail = email;
}
You might want to make getter/setter methods for access to above variables.
ArrayList<E>.get(i) performs virtually the exact same function as [] in static arrays. The only difference between the two is that ArrayList<E>.get(i) is simply adapted into the object context. In other words, you can dereference it.
First, you'll need to change the privacy of Customer's fields to public to give the ArrayList<Customers> object access to it.
Then you'll be able to retrieve your class' fields with simply:
customers.get(index).FirstName //or whatever other field

Creating an addContact() method that will create unique contacts each time

A school assignment (in beginner Java) is asking me to create a small contact manager program, which I'm having trouble with.
It asks us to create a few classes - Address, PhoneNumber, Contact, and ContactManager.
In ContactManager, we're asked to create a method called addContact() which will add a brand new unique contact to an object array within ContactManager.
However I cannot figure out how to make this method do what I want it to do since each time it creates a new Contact, it always has the same name. How do I make the object it creates have a unique name (i.e. Contact001, Contact002 etc) each time?
Also, how do I feed through all the relevant information it needs to create it, assuming I can enter all the data in instance variables to test it?
This is my code class:
public class Contact {
//Contact Instance Variables
private String lastName;
private String firstName;
private String middleName;
private Address completeAddress[];
private PhoneNumber phoneNumer[];
private SocialNetworkAccount socialNetworkInfo[];
public Contact(String lastName, String firstName, String middleName,
Address[] completeAddress, PhoneNumber[] phoneNumer,
SocialNetworkAccount[] socialNetworkInfo) {
this.lastName = lastName;
this.firstName = firstName;
this.middleName = middleName;
this.completeAddress = completeAddress;
this.phoneNumer = phoneNumer;
this.socialNetworkInfo = socialNetworkInfo;
}
"private List contacts;" is a declaration of an instance variable called contacts.
The variable's type is a List, which is a specific kind of Collection object found in the java.util package.
List<Contact> is a way of stating to the compiler that this list contains only Contact objects. See "Generics" in the java tutorial.
In your ContactManager class, define these
private List<Contact> contacts;
contacts = new ArrayList<Contact>(); //you should put this in ContactManager constructor
public void addContact(Contact contact) {
contacts.add(contact);
}
When you want to add a new contact
//just supply different names, etc. load the information from a file
contactManager.addContact(new Contact(name,surname,....));
or...
To add a couple of placeholder contacts...
int NUM_OF_CONTACTS = 2; //how many contacts to create
for(int i = 0; i < NUM_OF_CONTACTS; ++i) {
contactManager.addContact(new Contact(("Contact" + i),"Placeholder Surname",..);
}

Categories