Adding an object to an array in a separate class - java

edit:
I am looking to pass HomeBuyers Objects to my homeBuyers ArrayList in my CreditUnion class. The this.homeBuyers.add function throws a "cannot find symbol" error. I have tried making the firstName, lastName, and creditScore vars static and passing the object in with HomeBuyers(HomeBuyers.firstName, HomeBuyers.lastName, HomeBuyers.creditScore). That avoided errors but did not add the object to the ArrayList.
public class LabProgram {
public static void main(String[] args) {
CreditUnion cu = new CreditUnion();
cu.addHomeBuyer(new HomeBuyers("first","last",600));
}
}
public class HomeBuyers {
public String firstName;
public String lastName;
public int creditScore;
public HomeBuyers(String firstName, String lastName, int creditScore) {
this.firstName = firstName;
this.lastName = lastName;
this.creditScore = creditScore;
}
}
public class CreditUnion {
public ArrayList<HomeBuyers> homeBuyers;
public CreditUnion() {
this.homeBuyers = new ArrayList<>();
}
public void addHomeBuyer(HomeBuyers homeBuyers) {
this.homeBuyers.add(HomeBuyers(firstName, lastName, creditScore));
}

You have multiple problems here.
The right syntax for creating a new object is new HomeBuyers(...). Not HomeBuyers().
Separately, firstName doesn't exist as a variable in your addHomeBuyer method. The only variable that does exist is homeBuyers. You could write homeBuyers.firstName. However, you already have an instance of your class HomeBuyers. There is no need to make another one with identical values. this.homeBuyers.add(homeBuyers) would have done the job.
These questions are incredibly simplistic; stack overflow probably isn't the right venue. I suggest any of the many nice tutorials out there, they tend to take a little more time to explain things in an orderly fashion.

Related

About ArrayList in future use?

I am a java beginner and learning the oop concept. I already success to store the object value into a arraylist and i try to display the arraylist in the main method. But the problem is if i remove the add value code in the main method and display again the arraylist. The arraylist will show the null value which is []. Please help me and is this is my understanding problem or need to store in txtfile? database or what to get the or store the arraylist and can use for display all the record, update or delete that i add before
This is for my practice project and unuse the database to create a POS system based on oop concept. I had learn php and c# before and i do the same type project and not very confused because of using database. But now i feel confused how to use the java to create it and can has ability to create member, update member profile and etc based on oop concept. Please help me or give the suggestion. Very thank you.
my super class
class Person {
private List<Customer> customers;
private String name;
private String gender;
private String email;
public Person(){
}
public Person(List<Customer> customers){
this.customers = customers;
}
public Person(String name, String gender, String email){
***
}
public List<Customer> getCustomers(){
return customers;
}
public void addCustomer(Customer customer){
customers.add(customer);
}
//Getter
***
//Setter}
my subclass
class Customer extends Person{
private int custID;
private static int customerID = 10001;
public Customer(String name, String gender, String email,int custID){
super(name, gender, email);
this.custID = custID;
customerID++;
}
public int getCustID(){
return custID;
}
public static int getCustomerID(){
return Customer.customerID;
}
public String toString(){
return String.format("%d%30s%7s%30s\n", getCustID(), getName(), getGender(),getEmail());
}
}
My main method
public class POS {
public static void main(String[] args) {
Customer p1 = new
Customer("Halo","M","haloworld#gmail.com",Customer.getCustomerID());
Customer p2 = new
Customer("Haloo","F","halobitchworld#gmail.com",Customer.getCustomerID());
List<Customer> cList = new ArrayList<>();
cList.add(p1); //if remove
cList.add(p2); // if remove
Person customer = new Person(cList);
System.out.print(customer.getCustomers());
}
}
i expect if write the code in main like
{ Person person = new Person();
System.out.print(person);
}
will display the result that i add before
If you don't want to add the customers to an ArrayList in your main-function a good way to do it would be to set the List<Customer> static in your Person-class and adding the customers as they get created.
public class Person {
private static List<Person> customers = new ArrayList<>();
public static List<Person> getCustomers() {
return customers;
}
private String name;
private String gender;
private String email;
public Person(String name, String gender, String email) {
this.name = name;
this.gender = gender;
this.email = email;
customers.add(this);
}
/* getters */
}
now in your main()-function you only have to create the Customers and they automatically get added to the customers list and therefore you can then get them by calling the static function getCustomers()
public static void main(String[] args) {
Customer p1 = new Customer("Halo","M","haloworld#gmail.com",Customer.getCustomerID());
Customer p2 = new Customer("Haloo","F","halobitchworld#gmail.com",Customer.getCustomerID());
System.out.print(Customer.getCustomers());
}
To store them you would have to implement some kind of storage system like MySQL or simply a text file if you don't really have to access them from everywhere. You will find plenty of tutorials here on Stackoverflow in how to do that.
EDIT
#andy-turner pointed out that doing customers.add(this); inside a constructor really is a pain. So you could just create the ArrayList<Customer> in your Main-class and then work like this:
private static ArrayList<Customer> customers = new ArrayList<>();
public static void main(String[] args) {
customers.add(new Customer("Halo","M","haloworld#gmail.com",Customer.getCustomerID()));
customers.add(new Customer("Haloo","F","halobitchworld#gmail.com",Customer.getCustomerID()));
System.out.print(customers);
}
Variables in memory are ephemeral
An ArrayList, like all of the Java Collections Framework, is a structure for holding data in memory. When your program ends its execution, all of that memory is freed. Your ArrayList is destroyed.
Storage
If you want to share data between runs, you must store it.
You can open a file in storage and write data values as text. On next run, read that file, parse the text back into objects, and populate a new ArrayList.
You can open a file and have your ArrayList write itself to storage using Java Serialization technology. Or you can do the serialization yourself with another serialization format.
Or send your data values to a database, which in turn writes them to storage. On next run, retrieve from database.
Or pass your data over the network to some service which accepts the data on your behalf. On next run, ask the service for your data.
All of this is too broad to discuss on Stack Overflow. You need to do your own research and learning.
Empty array versus NULL
The arraylist will show the null value which is [].
The string [] represents an empty array, an array holding no elements. Such array is not null! Null means no array at all.
Imagine a bookshelf holding books. That’s like an array holding elements. Remove the books. The empty shelf is like an empty array, with no elements. Now take down the bookshelf and burn it. That’s a null array, meaning no array at all.

Loop over object setters java [duplicate]

This question already has answers here:
Invoking all setters within a class using reflection
(4 answers)
Closed 5 years ago.
I have a POJO object and a collection of appropriate data.
import java.util.ArrayList;
import java.util.List;
public class TestPojo {
private String name;
private String number;
private String id;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public static void main(String[] args) {
TestPojo test = new TestPojo();
List<String> sampleData = new ArrayList<>();
sampleData.add("Bob");
sampleData.add("641-613-623");
sampleData.add("id-1451");
sampleData.add("Male");
test.setName(sampleData.get(0));
test.setNumber(sampleData.get(1));
test.setId(sampleData.get(2));
test.setSex(sampleData.get(3));
}
}
My question is how can i fill my POJO object with data in a loop? Is it posible to iterate all object setters and set data from List in appropriate places? I know that reflection can help in this case.
Here is an simple example to call setters via reflection (which needs to be adjusted):
[if this is a good approach, is another question. But to answer your question:]
public static void main(String[] args) throws Exception
{
//this is only to demonstrate java reflection:
Method[] publicMethods = TestPojo.class.getMethods(); //get all public methods
TestPojo testObj = TestPojo.class.newInstance(); //when you have a default ctor (otherwise get constructors here)
for (Method aMethod : publicMethods) //iterate over methods
{
//check name and parameter-count (mabye needs some more checks...paramter types can also be checked...)
if (aMethod.getName().startsWith("set") && aMethod.getParameterCount() == 1)
{
Object[] parms = new Object[]{"test"}; //only one parm (can be multiple params)
aMethod.invoke(testObj, parms); //call setter-method here
}
}
}
You can also save all setter-methods in an list/set for later re-use...
But as others already said, you have to be careful by doing so (using reflection)!
Cheers!
You can't easily - and you shouldn't.
You see, your POJO class offers some setters. All of them have a distinct meaning. Your first mistake is that all of these fields are strings in your model:
gender is not a string. It would rather be an enum.
"number" is not a string. It should rather be int/long/double (whatever the idea behind that property is)
In other words: you premise that "input" data is represented as array/list is already flawed.
The code you have written provides almost no helpful abstractions. So - instead of worrying how to call these setter methods in some loop context - you should rather step back and improve your model.
And hint: if this is really about populating POJO objects from string input - then get your string into JSON format, and use tools such as gson or jackson to do that (reflection based) mapping for you.
"Iterating over methods" seems pretty much of a wrong idea in OO programming. You could simply add a constructor to your class setting all of your attributes, and then just call that constructor in a loop as desired to create new objects with data you desire.
In your class define:
public TestPojo(String name, String number, String id, String sex){
this.name = name;
this.number = number;
this.id = id;
this.sex = sex;
}
Also using a List makes no much sense here. I'd recommend using a HashMap to then iterate over it in a for loop making proper calls of the above constructor.

How to transfer input data from a private void GUI to an ArrayList in a java class?

I need help with a specific problem in my class project. The goal of the project is to create a program in which you can register how much shares you own. Information that's required is the company name, how many shares you own and their respective value. I created a GUI class and a class where the information is transferred to. The input comes from a private void. I'm having trouble finding a way to transfer the input from the private void to a an arraylist in a class outside it.
Here is how I initialized the arraylist in the GUI class.
public class GUISharePortfolio_1 extends javax.swing.JFrame {
ArrayList<SharePackage.Share> Package = new ArrayList<SharePackage.Share>();
Next is how I get the company name, number of shares and their value from the GUI. Since it is a private void I have to transfer that information to the SharePackage class.
private void CreatePortfolioButtonActionPerformed(java.awt.event.ActionEvent evt) {
String name;
double number;
double value;
name = CompanyNameField.getText();
number = Double.parseDouble(NumberOfSharesField.getText());
value = Double.parseDouble(ValueOfShareField.getText());
Package.CompanyName(name);
Package.NumberOfShares(number);
Package.ValueOfShare(value);
}
I'm getting an error saying "cannot find symbol" under the CompanyName, NumberOfShares and ValueOfShare.
The public class to which the info should be transferred is this:
package shareportfolio;
import java.util.ArrayList;
public class SharePackage
{
private ArrayList<Share> Package = new ArrayList<Share>();
public class Share
{
private String companyname;
private double numberofshares;
private double valueofshare;
Share(String companyname, double numberofshares, double valueofshare)
{
this.companyname = companyname;
this.numberofshares = numberofshares;
this.valueofshare = valueofshare;
}
public void setCompanyName(String name)
{
companyname = name;
}
public String getCompanyName()
{
return(companyname);
}
public void setNumberOfShares(double number)
{
numberofshares = number;
}
public double getNumberOfShares()
{
return(numberofshares);
}
public void setValueOfShare(double value)
{
valueofshare = value;
}
public double getValueOfShare()
{
return(valueofshare);
}
}
}
I would appreciate any help very much.
You have a field named Package, who's type is ArrayList. ArrayList doesn't have a method called CompanyName. What you're probably trying to do is something like:
Package.add(new SharePackage.Share(companyname, numberofshares, valueofshares));
You have two such fields named 'Package', so not sure which one you're trying to add to. Maybe you're under the impression the fields are somehow the same one. They are not.
BTW: Definitely learn Java coding style before submitting this to anyone. You are naming fields with UpperCamelCase which makes it very difficult for a java programmer to read your code.
user1207705 that was the answer. I modified it to:
String name;
double number;
double value;
name = CompanyNameField.getText();
number = Double.parseDouble(NumberOfSharesField.getText());
value = Double.parseDouble(ValueOfShareField.getText());
Package.add(new SharePackage.Share(name, number, value));
Thank you for your help and I will work on Java coding style.

Adding Objects to an ArrayList without error

I am just trying to add some objects to an ArrayList in eclipse, but i keept getting an error (Syntax error, insert "... VariableDeclaratorId" to complete FormalParameterList) under the 'persons.add(one);'. Any idea what I am doing wrong?
package thequestion;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class PersonComparator implements Comparator<Person>{
#Override
public int compare(Person o1, Person o2) {
return 0;
}
Person one = new Person("Kevin", "Gresmer");
List<Person> persons = new ArrayList<Person>();
persons.add(one);
public void sortByLastName(List people) {
Comparator comp = new PersonComparator();
Collections.sort(people, comp);
}
}
public class Person {
private String firstName = null;
private String lastName = null;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
The line persons.add(one) is a statement, and you can't have a statement outside a block of code (method, constructor, etc.). Also, your Comparator should contain code related to the comparison you are doing. I don't think it's the right place to store a list or implement the sortByLastName() method.
You can only initialize the instance variables in class and outside the methods.
You initialized persons. Then to apply methods, you need to put that line into some methods. So, may be you can update your Sort Method or create new one and make reference to that method from your sort method.
The first option as explained in the above comment.
class PersonComparator implements Comparator{
#Override
public int compare(Person o1, Person o2) {
return 0;
}
Person one = new Person("Kevin", "Gresmer");
List<Person> persons = new ArrayList<Person>();
private void addPersons(){
persons.add(one);
}
//persons.add(one);
public void sortByLastName(List people) {
addPersons();
Comparator comp = new PersonComparator();
Collections.sort(people, comp);
}
}
The point is we cannot write anything except the Instance variables. We have to cover them with methods. I hope this will solve your issue.
put below under sortByLastName method. Currently below code snippet not lying under any method.
persons.add(one);
Correct code should be
public void sortByLastName(List people) {
persons.add(one);
Comparator comp = new PersonComparator();
Collections.sort(persons , comp);
}
please note :- But my answer is in terms of compilation error. Ideally comparator should have code only related to comparison. Nothing else.
Obviously, you cannot do persons.add(...) in the middle of the class declaration.
You should certainly add one and persons in a main in the class Person, and keep your Comparator class clean with only the logic of comparison. The main will allow you to test your code.
The same idea for the sortByLastName(...) you can declare it as static in Person class.
Then you can test with the main, e.g.
// In class `Person`
public static void main(String[] args) {
List<Person> persons = new ArrayList<Person>();
Person one = new Person("Kevin", "Gresmer");
persons.add(one);
Person two = new Person("Elvis", "Presley");
persons.add(two);
System.out.println(sortByLastName(persons));
}
Note for the above to provide a sensible output, you need to add a toString() method to the Person class.

How to use Parcelable for a class which has multiple constructors?

Well, i was trying to pass arraylist of objects from one activity to another. I have 2 constructors in the class Student.
If, i use, Serializable than the code is like below:
#SuppressWarnings("serial")
public class Student implements Serializable
{
private int studentdID;
private String studentName;
private String studentDept;
public Student(){}
public Student(String name, String dpt)
{ this.studentName = name;
this.studentDept = dpt;}
public Student(int id, String name, String dpt)
{ this.studentdID = id;
this.studentName = name;
this.studentDept = dpt; }
public int getstudentdID() { return studentdID; }
public void setstudentdID(int studentdID) {this.studentdID = studentdID;}
public String getstudentName() { return studentName;}
public void setstudentName(String studentName) {this.studentName = studentName;}
public String getstudentDept() { return studentDept; }
public void setstudentDept(String studentDept) { this.studentDept = studentDept;}
}
But the problem i am facing is that how am i going to do this with parcelable? How am i going to set the values of the variables in class-like i did with Serializable? I mean separately using 2 constructors-one without ID another without the ID?
Did you read how Parcelable works?
You need only one constrcutor for parcelable to read what you pass to it, and Parcelable interface will add a method writeToParcel where you put the data to save.
It's not an automatic process like Serializable, everything is up to you.
The constructor which Parcelable will use will accept only one argument Parcel where you will find some methods like read*(KEY) to read back values.
And in writeToParcel you will write in the Parcel (the argument of the method) the values you want pass to pass with write*(KEY, VALUE).
Parcelable don't care about your constructors or fields.
P.S You will need a CREATOR too. Read some tutorial online to know more about it if you need.
Marco's answer explains why Parcelable doesn't automatically decide what constructor to use - it can't.
However, there is a way around this. Use Parcel.dataAvail(), which
Returns the amount of data remaining to be read from the parcel. That
is, dataSize()-dataPosition().
For example,
public Student(){}
public Student(String name, String dpt)
{
this.studentName = name;
this.studentDept = dpt;}
public Student(int id, String name, String dpt)
{ this.studentdID = id;
this.studentName = name;
this.studentDept = dpt;
}
public Student(Parcel in) {
name = in.readString();
dpt = in.readString();
if(in.dataAvail() > 0) // is there data left to read?
id = in.readInt();
}
^ The above constructor will allow for the necessary variables to be instantiated correctly. Also, you define writeToParcel() something like:
public void writeToParcel(Parcel out) {
out.writeString(name);
out.writeString(dpt);
//0 is the default value of id if you didn't initialize it like
// in the first constructor. If it isn't 0, that means it was initialized.
if(id != 0)
out.writeInt(id);
}
Of course, you'll need to define your CREATOR like so:
public static final Parcelable.Creator<Student> CREATOR = new Parcelable.Creator<Student>() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
#u3l solution is not required..how many constructors are there it doesn't matter.
simple it works go as normal implementation.
I mean no special care is required when multiple constructors present in parcelable.

Categories

Resources