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
Related
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;
I am using Selma and I have the following class:
public class Customer
{
private int id;
private String email;
private String firstName;
private String lastName;
private Date registeredDate;
private List<Address> addresses;
}
I want to map it to:
public class Customer
{
private String id;
private String email;
private String firstName;
private String lastName;
private Date registeredDate;
private String company;
private Address address1;
private Address address2;
}
Is there any way to cast the (int) id to (String) id and to set the first address from the List to address1 and the second address to address2?
I was thinking of using an interceptor, but this way I will have to manually map the Address classes. Is there a way to use Selma to automatically map the address classes in the interceptor? For example:
public class CustomerCustomMapper
{
public void interceptMyCustomerToCustomer(com.mycode.domain.Customer source, Customer destination) {
if(source.getAddresses() != null && source.getAddresses().size() > 0)
{
com.mycode.domain.Address myAddress1 = source.getAddresses().get(0);
AddressMapper addressMapper = Selma.builder(AddressMapper.class).build();
Address address1 = addressMapper.mapAddress(myAddress1);
destination.setAddress1(address1);
// do the same for address2
}
}
EDIT
Regarding mapping the Address class I did it the way I showed above. I created an AddressMapper with the following code inside: Address toAddress(com.mycode.domain.Address address);
Then I created an addressMapper and used it to map the Address autimatically:
AddressMapper addressMapper = Selma.builder(AddressMapper.class).build();
As for the id, currently I have to create an interceptor for every class that I map (almost every class has an Id in it (SQL)), and manually set the id like so: destination.setId(Integer.toString(source.getId()));
It is quite frustrating actually, but sadly I can't find a better option.
for the list to Address the interceptor is the good answer.
For the int to String you can specify a custom mapper mapping from int to String (see http://www.selma-java.org/#custom-mapper).
But I would recommend using an abstract mapper instead of building a new mapper to map the Address. This way you'll be able to integrate your specific code inside the mapper and call the address mapper method directly (see http://www.selma-java.org/#abstract-mapper).
For the toString thing, you can also add a feature request to Github. I'll be glad to add this feature.
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());
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);
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",..);
}