This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 1 year ago.
I have an array in the main class which holds Employee class objects. I'm trying to generate a unique ID for each object but it is printing the same ID for all the objects
Main class:
public static void main(String[] args) {
Employee employee1 = new Employee("Luke", 36);
Employee employee2 = new Employee("Martin", 49);
Employee employee3 = new Employee("Kevin", 21);
Employee employee4 = new Employee("Sam", 43);
Employee employee5 = new Employee("Nicole", 45);
Employee employee6 = new Employee("Linta", 21);
Employee[] allEmployees = { employee1, employee2, employee3, employee4, employee5, employee6 };
for (int i = 0; i < allEmployees.length; i++) {
System.out.println(allEmployees[i]);
}
}
Employee class
public class Employee {
private String name;
private int age;
private static String employeeID = "0";
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = getNextUniqueID();
}
public String getName() {
return name;
}
public String setName(String name) {
this.name =name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public static String getNextUniqueID() {
int id = Integer.parseInt(employeeID);
++id;
return Integer.toString(id);
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
}
I want the employeeID as string and I can't use java.util.UUID; for my project.
You need a static variable associated with the class to maintain the unique id and an instance variable to keep that particular employee's ID in the class.
private String employeeID; // instance member
private static String uniqueID = "0"; // static class variable
public static String getNextUniqueID() {
int id = Integer.parseInt(uniqueID); // get the static variable
++id; // increment it
uniqueID = Integer.toString(id); // update the static variable
return uniqueID; // return the value to use for the employee
}
Then in the Employee constructor, use the static member:
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = Employee.getNextUniqueID();
}
updated Employee class:
public class Employee {
private String name;
private int age;
private String employeeID;
private static String uniqueID = "0";
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = Employee.getNextUniqueID();
}
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 static String getNextUniqueID() {
int id = Integer.parseInt(uniqueID);
++id;
uniqueID = Integer.toString(id);
return uniqueID;
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
}
Output:
Luke 36 1
Martin 49 2
Kevin 21 3
Sam 43 4
Nicole 45 5
Linta 21 6
You should store last generated id in static field but use non static for id of certain employee.
Also you should use AtomicInteger type for thread safety which you can convert to String. Check that:
import java.util.concurrent.atomic.AtomicInteger;
public class Employee {
private String employeeID;
private String name;
private int age;
private static AtomicInteger lastGeneratedId = new AtomicInteger(0);
Employee(String name, int age) {
this.name = name;
this.age = age;
employeeID = getNextUniqueID();
}
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 static String getNextUniqueID() {
return String.valueOf(lastGeneratedId.incrementAndGet());
}
public String getEmployeeID() {
return employeeID;
}
public String toString() {
return getName() + " " + getAge() + " " + getEmployeeID();
}
public static void main(String[] args) {
Employee employee1 = new Employee("Luke", 36);
Employee employee2 = new Employee("Martin", 49);
Employee employee3 = new Employee("Kevin", 21);
Employee employee4 = new Employee("Sam", 43);
Employee employee5 = new Employee("Nicole", 45);
Employee employee6 = new Employee("Linta", 21);
Employee[] allEmployees = { employee1, employee2, employee3, employee4, employee5, employee6 };
for (int i = 0; i < allEmployees.length; i++) {
System.out.println(allEmployees[i]);
}
}
}
Related
I have 2 classes
Mother and Newborn
Class Mother:
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class Mother extends NewBorn {
private List<NewBorn> newBornList = new ArrayList<>();
private Set<NewBorn> children;
private int id;
private String name;
private int age;
public Mother(Mother mother, List<NewBorn> newBornList, Set<NewBorn> children, int id, String name, int age) {
super(mother);
this.newBornList = newBornList;
this.children = children;
this.id = id;
this.name = name;
this.age = age;
}
public Mother(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public Mother(int id, String gender, String name, int birthdate, int weight, int height, List<NewBorn> newBornList, Set<NewBorn> children, int id1, String name1, int age) {
super(id, gender, name, birthdate, weight, height);
this.newBornList = newBornList;
this.children = children;
this.id = id1;
this.name = name1;
this.age = age;
}
public List<NewBorn> getNewBornList() {
return newBornList;
}
public void setNewBornList(List<NewBorn> newBornList) {
this.newBornList = newBornList;
}
public Set<NewBorn> getChildren() {
return children;
}
public void setChildren(Set<NewBorn> children) {
this.children = children;
}
#Override
public int getId() {
return id;
}
#Override
public void setId(int id) {
this.id = id;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "Mother{" +
"newBornList=" + newBornList +
", children=" + children +
", id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
Class NewBorn:
public class NewBorn {
private Mother mother;
public NewBorn(Mother mother) {
this.mother = mother;
}
public NewBorn() {
}
public Mother getMother() {
return mother;
}
public void setMother(Mother mother) {
this.mother = mother;
}
private int id;
private String gender;
private String name;
private int birthdate;
private int weight;
private int height;
private int motherId;
public NewBorn(int id, String gender, String name, int birthdate, int weight, int height) {
this.id = id;
this.gender = gender;
this.name = name;
this.birthdate = birthdate;
this.weight = weight;
this.height = height;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getBirthdate() {
return birthdate;
}
public void setBirthdate(int birthdate) {
this.birthdate = birthdate;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public int getMotherId() {
return motherId;
}
public void setMotherId(int motherId) {
this.motherId = motherId;
}
#Override
public String toString() {
return "NewBorn{" +
"mother=" + mother +
", id=" + id +
", gender='" + gender + '\'' +
", name='" + name + '\'' +
", birthdate=" + birthdate +
", weight=" + weight +
", height=" + height +
", motherId=" + motherId +
'}';
}
}
I have to get the mother older then 25years old that have child more then 4000g weigth
I did the following
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) throws IOException {
List<Mother> motherabove = above25YoAndChildHeavierThen4000g(mothers, newBorns);
System.out.println("List with mothers above 25 years old and childs that are over 4000g weigth: " + motherabove + "\n");
}
public static List<Mother> parseMotherFileTxt() throws IOException {
List<Mother> mothers = new ArrayList<>();
BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\mamy.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] s = line.split("\\s");
mothers.add(new Mother(Integer.parseInt(s[0]), s[1], Integer.parseInt(s[2])));
}
bufferedReader.close();
return mothers;
}
public static List<NewBorn> parseNewBornFileTxt() throws IOException {
List<NewBorn> newBorn = new ArrayList<>();
BufferedReader bufferedReader = new BufferedReader(new FileReader("src\\noworodki.txt"));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] s = line.split("\\s");
newBorn.add(new NewBorn(Integer.parseInt(s[0]), s[1], s[2], Integer.parseInt(s[4]), Integer.parseInt(s[5]), Integer.parseInt(s[6])));
}
bufferedReader.close();
return newBorn;
}
public static List<Mother> above25YoAndChildHeavierThen4000g(List<Mother> motherList, List<NewBorn> newBornList) {
return motherList.stream()
.filter(mother -> mother.getAge() > 25)//over 25yo
.filter(mother -> mother .getMotherId() == newBorn.getId())//get mother that have same id as child so assuming that means that this is the mother of the child
.filter(newBorn-> newBorn.getWeight() > 4000)//child over 4000g
.collect(Collectors.toList());// I expect to collect all the filters and return the correct output : Example Mother is : 112 Laura 38
and she have a child : 29 s Gabriel 1999-11-16 4100 54 112 = where 112 is the mother id that `I know is child of the mother`
}
I think something is wrong in the relation between the classes because I assume that the filter should work just fine if everything else is ok.
Normally should have mother has a list of children and a specific child has a field mother so with this I should be able to filter through.
I think you are looking for something like:
public static List<Mother> above25YoAndChildHeavierThen4000g(List<Mother> motherList, List<NewBorn> newBornList) {
return motherList.stream()
.filter(mother -> mother.getAge() > 25)
.filter(mother -> mother.getChildren().stream()
.anyMatch(child -> child.getWeight() > 4000))
.collect(Collectors.toList());
}
However the code overall definitely needs cleaning as advised in the comments
public List motherMoreThan() {
List list = new ArrayList<>();
for (Mother mother : mothers) {
if (mother.getAge() > 25 && isChildOver4000(mother)) {
list.add(mother);
}
}
return list;
}
public boolean isChildOver4000(Mother mother) {
for (Newborn newborn : mother.getList()) {
if (newborn.getWeight() > 4000) {
return true;
}
}
return false;
}
you can call them like this :
System.out.println("\nMothers over 25 Years old with childer heavier than 4000g;");
app.motherMoreThan()
.forEach(System.out::println);
I have a List and a Map as below:
public class student {
private String name;
private String age;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
student(String id,String name,String age)
{
}
}
List<student> stulist = Arrays.asList(new student("1", "vishwa",null),
new student("3", "Ravi",null),
new student("2", "Ram",null));
Map<String,String> newmap = new HashMap() {
{
put("1","20");
put("2","30");
}
};
I am comparing like this: If id in map matches the id in list then add
age from Map to age of List.
I have tried this so far , but i am not able to get it.
newmap.entrySet().stream().filter(entry->entry.getKey().equals(student::getId)).collect(..collect here to list..);
stulist = stulist.stream().map(instance -> {
student studentInstance = instance;
studentInstance.setAge(newMap.getOrDefault(studentInstance.getId(),"<default age>"));
return studentInstance;
}).collect(Collectors.toList()); ;
ps: Use proper naming conventions. Change the class name student to Student.
Here is solution, assuming I got the question right:
import java.util.*;
import java.util.stream.*;
public class Answer {
public static void main(String[] args) {
List<Student> studentsWithoutAge = Arrays.asList(
new Student("1", "Vishwa", null),
new Student("3", "Ravi", null),
new Student("2", "Ram", null)
);
Map<String,String> ageById = new HashMap() {{
put("1","20");
put("2","30");
}};
List<Student> studentsWithAge = addAge(studentsWithoutAge, ageById);
System.out.println("Students without age: " + studentsWithoutAge);
System.out.println("Students with age: " + studentsWithAge);
}
static List<Student> addAge(List<Student> students, Map<String,String> ageById) {
return students.stream()
.map(student -> {
String age = ageById.getOrDefault(student.getId(), null);
return new Student(student.getId(), student.getName(), age);
})
.collect(Collectors.toList());
}
}
class Student {
private String name;
private String age;
private String id;
Student(String id,String name,String age){
this.id = id;
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return String.format("Student: id = %s, name = %s, age = %s", this.id, this.name, this.age);
}
}
Implement Student class as #Zgurskyi comment, and then use this on main:
stulist.forEach(stu -> {
stu.setAge(newmap.getOrDefault(stu.getId(), null));
});
Use Collectors.toList()
// Accumulate names into a List
List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());
I'm new to programming and i'd like some help.
I want to make a class that can add name,age and multiple phone numbers ( in some cases it will be 1, in others 4, etc...) and then show all the info.
I don't want to make it by creating another class for the ArrayList,
I'd like to do it all inside this class, I guess it's something simple to do but I can't figure this out and I'm not finding the solution I want.
what can I do about it? thx in advance, first time posting If I did something wrong please tell me.
import java.util.ArrayList;
public class Athlete
{
private String name;
private int age;
private ArrayList<String> phones = new ArrayList();
public Athlete(String name, int age)
{
this.name = name;
this.age = age;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public ArrayList<String> getPhones()
{
return phones;
}
public void setPhones(ArrayList<String> phones)
{
this.phones = phones;
}
#Override
public String toString()
{
return "Athlete{" + "name=" + name + ", age=" + age + ", phones=" + phones + '}';
}
}
You could make an inner class for PhoneList and use that type instead of directly working with the ArrayList.
public class Athlete
{
private String name;
private int age;
private PhoneList phoneList;
public Athlete(String name, int age)
{
this.name = name;
this.age = age;
phoneList = new PhoneList();
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
// Maybe just return the toString (or a read only list)
public PhoneList getPhones()
{
return phoneList;
}
publicvoid addPhone(String phone)
{
phoneList.add(phone);
}
#Override
public String toString()
{
return "Athlete{" + "name=" + name + ", age=" + age + ", phones=" + phoneList + '}';
}
private class PhoneList
{
private ArrayList<String> list = new ArrayList<String>();
private void add(String phone)
{
list.add(phone);
}
#Override
public String toString()
{
StringBuffer b = new StringBuffer(32);
for (String ph : list)
{
b.append(ph + "\n"); // Or something
}
return b.toString();
}
}
}
Hi I have created a toStringmethod in one of my classes which can be seen below.
Student Class:
package Practical5;
public class Student extends Person {
//instance variables
private static int MAX_MODULES = 6;
private StudentMode modeOfStudy;
private boolean studentLoan;
private int numEnrolledModules;
//constructor
public Student(String name, String dob, Address address, StudentMode modeOfStudy, boolean studentLoan) {
super(name, dob, address);
this.modeOfStudy = modeOfStudy;
this.studentLoan = studentLoan;
this.numEnrolledModules = 0;
}
//accessors & mutators
public StudentMode getMode() {
return modeOfStudy;
}
public boolean isStudentLoan() {
return studentLoan;
}
public int getNumEnrolledModules() {
return numEnrolledModules;
}
public void setMode(StudentMode modeOfStudy) {
this.modeOfStudy = modeOfStudy;
}
public void setStudentLoan(boolean studentLoan) {
this.studentLoan = studentLoan;
}
public void setNumEnrolledModules(int numEnrolledModules) {
this.numEnrolledModules = numEnrolledModules;
}
#Override
public void purchaseParkingPass() {
System.out.println(getName() + " just purchased a parking pass with student discount.");
}
#Override
public void addModule(String moduleCode) {
if (getNumEnrolledModules() < MAX_MODULES) {
System.out.println(getName() + " successfully registered for the module: " + moduleCode);
}
else {
System.out.println("You are unable to register for " + moduleCode + " as the maximum number of permitted module enrolments has been reached.");
}
}
public String toString() {
return "Student [ ID: " + getId() + "; Name: " + getName() +
"; DOB: " + getDob() + "; Study Mode: " + getMode() +
"; Number of Enrolled Modules: " + getNumEnrolledModules();
}
}
Person Class:
package Practical5;
public abstract class Person {
//instance variables
private static int LAST_ID = 1000 + 1;
private int id;
private String name;
private String dob;
private Address address;
//constructor
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
//accessors & mutators
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getDob() {
return dob;
}
public Address getAddress() {
return address;
}
public void setName(String name) {
this.name = name;
}
public void setDob(String dob) {
this.dob = dob;
}
public void setAddress(Address address) {
this.address = address;
}
//methods
public abstract void purchaseParkingPass();
public abstract void addModule(String moduleCode);
}
I then created a tester class and created a new ArrayList and added these elements to it.
I then created a for loop in order to loop through each element and call the toString method to print out the details of each element but it is returning null values.
Tester Class:
package Practical5;
import java.util.ArrayList;
import java.util.Scanner;
public class UIS_Tester {
public static void main(String[] args) {
Student student1 = new Student("James Black", "07/09/1995" , new Address("Wheeler's Road",10,"Belfast", "BT12 5EG", "Co.Antrim"),StudentMode.Fulltime, false);
Student student2 = new Student("Adam Smith", "12/11/1979" , new Address("Ivy Hill",67,"Belfast", "BT17 7BN", "Co.Antrim"),StudentMode.Parttime, true);
ArrayList<Person> uniPeople = new ArrayList<Person>();
uniPeople.add(student1);
uniPeople.add(student2);
printMenu(uniPeople);
}
public static void printAllDetails(ArrayList<Person> uniPeople) {
for (int i = 0; i < uniPeople.size(); i++) {
System.out.println(uniPeople.get(i).toString());
}
}
}
Output:
Student [ ID: 1002; Name: null; DOB: null; Study Mode: Fulltime; Number of Enrolled Modules: 0
Student [ ID: 1003; Name: null; DOB: null; Study Mode: Parttime; Number of Enrolled Modules: 0
Can anyone help me with this problem? Thanks
public Person(String name, String dob, Address address) {
super();
LAST_ID ++;
this.id = LAST_ID;
}
The constructor completely ignores its three arguments. It doesn't assign them to the corresponding fields, so these fields keep their default value: null.
You have to store the name value in the constructor. Your version did not use the name value.
public Person(String name, String dob, Address address) {
super();
this.name = name; // <== important line
this.dob = dob; // <== important line
this.address = address; // <== important line
LAST_ID ++;
this.id = LAST_ID;
}
Look at the constructor in person and in student, Should use the parameters in the method header.
super(name,dob,address)
I have 5 classes (they're small). PersonDemo (test class), Person (superclass), and Student, Instructor and Graduate Student (sub classes). All the classes except for PersonDemo are finished.
I need to read in a file (data.txt) and store it to array Person. Then need I need to determine which object to initialize depending on the first value of the array. ( 1 - person, 2 - student, 3 - instructor or 4 - graduate student ) - I'm having trouble with this part.
Can someone point me in the right direction? My classes are below along with what the input file (data.txt) looks like and what the output file should look like.
PersonDemo.Java
public class PersonDemo
{
public static void main ()
{
JFileChooser chooser = new JFileChooser();
Scanner fileScanner = null;
Person [] ins = new Person [10];
try {
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
fileScanner = new Scanner(selectedFile);
while(fileScanner.hasNextLine())
{
// Need to load "data.txt" into array
// Then need I need to determine which object to initialize depending on the
// first value of the array in "data.txt"
//( 1 - person, 2 - student, 3 - instructor or 4 - graduate student )
}
fileScanner.close();
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not find file");
}
}
public static void showAll(Person [] ins)
{
// Future code here
}
}
Person.java (superclass)
public class Person
{
private String name;
private int age;
public Person()
{
name="";
age=0;
}
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
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 String toString()
{
return "Name: " + name + "\t" + "Age: " + age;
}
}
Student.java (subclass)
public class Student extends Person
{
private int studentID;
private String major;
public Student()
{
studentID = 0;
major = "";
}
public Student(String name, int age, int studentID, String major)
{
super(name, age);
this.major = major;
this.studentID = studentID;
}
public int getID()
{
return studentID;
}
public void setID(int studentID)
{
this.studentID = studentID;
}
public String getMajor()
{
return major;
}
public void setMajor(String major)
{
this.major = major;
}
public String toString()
{
return super.toString() + "Student ID: " + studentID + "Major: " + major;
}
}
GraduateStudent.java (subclass)
public class GraduateStudent extends Student
{
private String researchArea;
public GraduateStudent()
{
researchArea = "";
}
public GraduateStudent(String name, int age, int studentID, String major, String researchArea)
{
super(name, age, studentID, major);
this.researchArea = researchArea;
}
public String getArea()
{
return researchArea;
}
public void setArea(String researchArea)
{
this.researchArea = researchArea;
}
public String toString()
{
return super.toString() + "Research Area: " + researchArea;
}
}
Instructor.java (subclass)
public class Instructor extends Person
{
private int salary;
public Instructor()
{
salary = 0;
}
public Instructor(String name, int age, int salary)
{
super(name, age);
this.salary = salary;
}
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
public String toString()
{
return super.toString() + "Salary: " + salary;
}
}