I am trying to print "name" of an employee from a list of employees. Below is my pojo class.
import java.time.LocalDate;
public class Employee {
private String name;
private String empID;
private Designation designation;
private LocalDate dateOfJoining;
private int monthlySalary;
public Employee(String name, String empID, Designation designation, LocalDate dateOfJoining, int monthlySalary) {
super();
this.name = name;
this.empID = empID;
this.designation = designation;
this.dateOfJoining = dateOfJoining;
this.monthlySalary = monthlySalary;
}
public Employee() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmpID() {
return empID;
}
public void setEmpID(String empID) {
this.empID = empID;
}
public Designation getDesignation() {
return designation;
}
public void setDesignation(Designation designation) {
this.designation = designation;
}
public LocalDate getDOJ() {
return dateOfJoining;
}
public void setDOJ(LocalDate dOJ) {
dateOfJoining = dOJ;
}
public int getMonthlySalary() {
return monthlySalary;
}
public void setMonthlySalary(int monthlySalary) {
this.monthlySalary = monthlySalary;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((dateOfJoining == null) ? 0 : dateOfJoining.hashCode());
result = prime * result + ((designation == null) ? 0 : designation.hashCode());
result = prime * result + ((empID == null) ? 0 : empID.hashCode());
result = prime * result + monthlySalary;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (dateOfJoining == null) {
if (other.dateOfJoining != null)
return false;
} else if (!dateOfJoining.equals(other.dateOfJoining))
return false;
if (designation == null) {
if (other.designation != null)
return false;
} else if (!designation.equals(other.designation))
return false;
if (empID == null) {
if (other.empID != null)
return false;
} else if (!empID.equals(other.empID))
return false;
if (monthlySalary != other.monthlySalary)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
#Override
public String toString() {
return "Employee [name=" + name + ", empID=" + empID + ", designation=" + designation + ", DOJ=" + dateOfJoining
+ ", monthlySalary=" + monthlySalary + "]";
}
}
Now while I am trying to print the "name", I am getting null value.
Please see as below,
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Employecomparable {
public static void main(String[] args) {
JoiningDate jd = new JoiningDate();
Employee emp = new Employee();
List<Employee> listofemployee = new ArrayList<>();
listofemployee.add(new Employee("abc", "12345", Designation.ASE,jd.date1 , 20000));
listofemployee.add(new Employee("abcd", "24680", Designation.SE, jd.date2, 30000));
listofemployee.add(new Employee("abcde", "13570", Designation.SSE,jd.date3, 40000));
listofemployee.add(new Employee("abcdef", "13690", Designation.TL, jd.date4, 60000));
listofemployee.add(new Employee("xyz", "10909", Designation.AM, jd.date5, 800000));
listofemployee.add(new Employee("koool", "89076", Designation.M, jd.date6, 2000));
System.out.println("The name of employee is "+emp.getName());
I am getting the output as "null".
In console I get, The name of employee is null.
How do i print the name?
Please help!
To print the name of a particular employee, kindly update the emp object.
emp = listofemployee.get(indexWithinTheList);
System.out.println("The name of employee is "+emp.getName());
Example:
emp = listofemployee.get(0);
System.out.println("The name of employee is "+emp.getName());
Output : The name of employee is abc
You may want to iterate over your employee and then print the name. Reason you get null is you created Employee object with default constructor. Which would mean name being string object would take default null value which is what you see.
If you want to print employee names, you could do the following:
for (Employee employee: listofemployee) {
System.out.println("The name of employee is " + employee.getName());
}
Since you are using List interface, you can access individual object by it's index. E.g. to get first employee name:
System.out.println("The name of employee is " + listofemployee.get(0).getName());
The error you are getting is because you have created the Employee object like below.
Employee emp = new Employee(); After that you are populating the list using new Employee. But you have not set any value to variable emp.so getName from emp will return null. If you want to get the value from emp. You first need to set the name using emp.SetName("Any name"); No you will get the value using emp.getName();
1 - Create Employee object like below:-
Employee emp =new Employee("xyz", "10909", Designation.AM, jd.date5,
800000);
2 - Then store into list.
3 - After that iterate over list and print result as per your requirement.
public static void main(String[] args) {
JoiningDate jd = new JoiningDate();
Employee emp = new Employee();
List<Employee> listofemployee = new ArrayList<>();
emp = new Employee("abc", "12345", Designation.ASE,jd.date1 , 20000);
listofemployee.add(emp);
emp =new Employee("abcd", "24680", Designation.SE, jd.date2, 30000);
listofemployee.add(emp);
emp =new Employee("abcde", "13570", Designation.SSE,jd.date3, 40000);
listofemployee.add(emp);
emp = new Employee("abcdef", "13690", Designation.TL, jd.date4, 60000);
listofemployee.add(emp);
emp =new Employee("koool", "89076", Designation.M, jd.date6, 2000);
listofemployee.add(emp);
emp =new Employee("xyz", "10909", Designation.AM, jd.date5, 800000);
listofemployee.add(emp);
System.out.println("The name of employee is "+emp.getName());
Iterator<Employee> itr = listofemployee.iterator();
// checking the next element availabilty
while (itr.hasNext())
{
System.out.println("name " + (itr.next()).getName());
}
}
I have two different arrays oldUsers and newUsers containing instances of the class User. User contain firstname, lastname and age attributes. I want to know the number of oldUsers objects in the newUsers array that have the same attributes. Shall I use two for loops and compare the arrays one per one or is there a function that can do the same work ?
You first need to override equals() and hashCode(). Then you can implement an intersection() method.
Number of identical values: 2
------------------------------
- { 'firstname': 'Bob', 'lastname': 'Smith', 'age': 30 }
- { 'firstname': 'Robert', 'lastname': 'Brown', 'age': 51 }
Main
import java.util.*;
public class Main {
public static void main(String[] args) {
List<User> oldUsers = new ArrayList<User>();
List<User> newUsers = new ArrayList<User>();
List<User> intersect;
oldUsers.addAll(Arrays.asList(
new User("Bob", "Smith", 30),
new User("Tom", "Jones", 42),
new User("Robert", "Brown", 51),
new User("James", "Jones", 28)
));
newUsers.addAll(Arrays.asList(
new User("Robert", "Brown", 51), // Same
new User("Bob", "Smith", 30), // Same
new User("Tom", "Jones", 21),
new User("James", "Hendrix", 28)
));
intersect = intersection(oldUsers, newUsers);
System.out.printf("Number of identical values: %d%n%s%n",
intersect.size(), "------------------------------");
for (User user : intersect) {
System.out.printf("- %s%n", user);
}
}
// http://stackoverflow.com/a/5283123/1762224
public static <T> List<T> intersection(List<T> list1, List<T> list2) {
List<T> list = new ArrayList<T>();
for (T t : list1) {
if (list2.contains(t)) {
list.add(t);
}
}
return list;
}
}
User
public class User {
private String firstname;
private String lastname;
private int age;
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; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public User(String firstname, String lastname, int age) {
super();
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((firstname == null) ? 0 : firstname.hashCode());
result = prime * result + ((lastname == null) ? 0 : lastname.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
User other = (User) obj;
if (age != other.age) return false;
if (firstname == null) {
if (other.firstname != null) return false;
} else if (!firstname.equals(other.firstname)) return false;
if (lastname == null) {
if (other.lastname != null) return false;
} else if (!lastname.equals(other.lastname)) return false;
return true;
}
#Override
public String toString() {
return String.format("{ 'firstname': '%s', 'lastname': '%s', 'age': %d }",
firstname, lastname, age);
}
}
Alternative Methods
Set :: Retain All
public static <T> List<T> intersection(List<T> list1, List<T> list2) {
Set<T> set = new HashSet<T>(list1);
set.retainAll(new HashSet<T>(list2));
return new ArrayList<T>(set);
}
List :: Java 8 Filter Stream
public static <T> List<T> intersection(Collection<T> list1, Collection<T> list2) {
return list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
}
Assuming your User objects correctly implement equals() and hashCode(), I would use one of the lists' retainAll(Collection other) method to craft the intersection of both lists and then return its size.
If you have equals() and hashCode() implemented correctly, you can place all inputs from oldUsers array to Set and then check data from newUsers if they are in that Set or not. This will work in O(max(n, m)) (place data in Set is O(n), check newUsers if they are in Set is O(m), so you have O(n) + O(m) = O(max(n,m)), where n is size of oldUsers list and m is size of newUsers list).
For example:
private int numberOfSameUsers(ArrayList<User> oldUsers, ArrayList<User> newUsers) {
Set<User> oldUsersSet = new HashSet<>(oldUsers);
int counter = 0;
for (int i = 0; i < newUsers.size(); i++) if (oldUsersSet.contains(newUsers.get(i))) counter++;
return counter;
}
I've been working on my add method for a couple of hours now and seem to have hit a roadblock. My method is supposed to search through every node in the list to see if there is a matching employee number and if there isn't, add the object in order of employee number.
Unfortunately I cant even seem to add a node to the beginning or end of my list. I think I understand the logic. I have to search through my list for find where I want the node, then all I have to do is have the new node's link point the already existing one. I think that I'm either not creating the nodes properly or not linking them properly. Every time I try to test my code though, only one node appears in my list.
import java.util.*;
public class HumanResources
{
private EmployeeNode first;
employee data = new employee();
private class EmployeeNode
{
//data members of employeenode
private EmployeeNode link;
employee data = new employee();
private EmployeeNode()
{
data = null;
link = null;
}
private EmployeeNode (employee emp)
{
data = emp;
link = null;
}
}
public EmployeeNode search (employee search)
{
EmployeeNode current = first;
if (first == null)
{ return null;}
while((present != null) && (present.data != search))
{
present = present.link;
}
return present;
}
private EmployeeNode nextInList(EmployeeNode x)
{
return x.link;
}
public boolean isEmpty()
{
return ( first == null );
} // end of isEmpty()
public HumanResources()
{
first = null;
}
public HumanResources ( employee x)
{
this.data = x;
}
public boolean addEmployee( employee emp)
{
EmployeeNode current = new EmployeeNode();
current = first;
if (current == null)
{
first = new EmployeeNode(emp);
return true;
}
else
{
while(current.link != null)
{
EmployeeNode temp = new EmployeeNode();
temp.data = emp;
temp.link = current;
}
return true;
}
}
public Employee findEmployee(String EmpNumber)
{
EmployeeNode current = first;
if(first == null)
{
return null;
}
else{
while (current != null)
{
public String toString()
{
EmployeeNode display;
display = first;
String temp = "";
while(display != null)
{
temp += display.data + "\n";
display = display.link;
}
return temp;
}
}
And here is my employee class
import java.util.*;
/**
This class manipulate information relating to employees
*/
public class employee {
private String empNumber;
private String name;
private String department;
private double salary;
/**
Zero parameter constructor that sets the values to null
*/
public employee()
{
empNumber = null;
name = null;
department = null;
salary = 0.0;
}
/**
Four parameter constructor to initialize the data members to the give values
#param kempnumber Employee's ID number
#param kname Employee's name
#param kdepartment Employee's department name
#param ksalary Employee's salary
*/
public employee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
/**
copy constructor
*/
public employee (employee copy)
{
empNumber = copy.empNumber;
name = copy.name;
department = copy.department;
salary = copy.salary;
}
/**
Four parameter constructor to set data members to given value
#param kname Employee's name
#param kdepartment Employee's department name
#param ksalary Employee's salary
*/
public void setEmployee(String kempnumber, String kname, String kdepartment, double ksalary)
{
empNumber = kempnumber;
department=kdepartment ;
name = kname;
salary = ksalary;
}
public String getEmpNumber() {
return empNumber;
}
public void setEmpNumber(String empNumber) {
this.empNumber = empNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary)
{
this.salary = salary;
}
public String toString()
{
return (empNumber + " " + name + " " + department + " " +salary);
}
public boolean equals(employee compareto) {
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if (firstemployee == secondemployee) {
return true;
}
else {
return false;
}
}
public int compareTo(employee compareto)
{
int less = -1;
int same = 0;
int more = 1;
int firstemployee = Integer.parseInt(empNumber);
int secondemployee = Integer.parseInt(compareto.empNumber);
if(firstemployee > secondemployee)
{
return more;
}
else if(firstemployee == secondemployee)
{
return same;
}
else
{
return less;
}
}
}
For the addEmployee method, if you are adding to the front of the list you shouldn't need a while loop at all. Your 'first' variable is presumably maintaining a reference to the front of the loop, so all you need to do is create the employee, update the links and point 'first' towards it. Something like this...
public boolean addEmployee( employee emp){
if (first == null) {
first = new EmployeeNode(emp);
return true;
}
else { // first must != null
EmployeeNode temp = new EmployeeNode(emp); //create the new employee
temp.link = first; // link the new employee to the old employee at the front of the list
first = temp; //update the new front of list to be the new employee
return true;
}
}
Keep in mind though if you want to add it to the end of the list, you will need a while loop to search through the list and find the end before creating the new employee and updating the links.
If your getting confused with the links, try stepping through the code and drawing out the nodes with lines to represent the links to help get you used to visualising the linked list.
I'm having troubling organizing my list of employees. I just need to organize them according to their employee type (first two letters). Each object starts with the employee code which are the first two letters. This is what I need to separate the position types but for some reason I can't grab them.
Here is the file that I am creating the objects out of and storing them in the arrays.
PW_1234,James,Bond,01/02/10,1,10 PW_1235,John,Brown,02/03/10,2,10.5
PW_1236,Howard,Johnson,03/04/10,3,11
PW_1237,Francis,Themule,04/05/11,4,10.75
PW_1238,Mathew,Lewis,05/06/11,1,12.75
PW_1239,Mark,Bixton,05/13/11,2,13
PW_1242,Sarah,Glover,05/14/11,1,13.75 PW_1245,John,Doe,05/15/11,4,10.5
PW_1245,Mary,Doe,05/15/11,4,10.5
TL_1248,Abel,English,05/16/11,3,16.5,0.01,100,89
TL_1251,Eustis,Clauser,05/17/11,2,16,0.02,100,9
SU_1254,Henry,Hollowman,05/18/11,1,40000,0.01
PW_1240,Luke,Sailor,01/22/12,3,14.5 PW_1243,Jane,Baker,01/23/12,2,14
PW_1243,Jane,Baker,01/23/12,2,14
TL_1246,David,Brief,01/24/12,1,14.75,0.01,100,57
PW_1246,David,Doson,01/24/12,1,14.75
TL_1249,Baker,Anderson,01/25/12,4,11.5,0.01,100,100
TL_1252,Frank,Donson,01/26/12,3,17.5,0.02,100,39
SU_1255,Issac,Asimov,01/27/12,2,43000,0.02
SU_1256,Issac,Shoreman,01/28/12,3,39000,0.01
SU_1257,Issac,Roberts,01/29/12,4,35500,0.01
PW_1241,John,Candy,11/23/13,4,9.5 PW_1244,Kate,Smith,11/24/13,3,15.5
PW_1244,Kate,Handle,11/24/13,3,15.5
TL_1247,Samual,Dempky,11/25/13,2,15,0.01,100,10
TL_1250,Charley,Boman,11/26/13,1,15.75,0.01,100,50
TL_1253,George,Fritzmen,11/27/13,4,12.5,0.02,100,27
Here is the code:
private String makeEmployeeList()
{
String list = "";
for(int i=0; i < employees.length; i++)
{
list += "\n"+employees[i].toString();
if(employees[i]substring(0,2).equals("SU"))
{
list += "\n"+employees[i].toString();
}
}
return list;
}
**Here is how the employees array is created:
private Employee[] employees;
**Here is how everything is loaded into it.
public void loadEmployeesFromFile(String fileName)
{
File inFile = new File(fileName);
if(inFile.exists()) // MAKE SURE FILE EXISTS
{
try
{
BufferedReader inReader = new BufferedReader(new FileReader(inFile));
inReader.mark(32000);
String inLine = inReader.readLine();
//************************************
// Counting rows to set array size
//************************************
int rowCount = 0;
while (inLine != null && !inLine.equals(""))
{
rowCount++;
inLine = inReader.readLine();
}
inReader.reset();
//*******************
// re-reading data
//*******************
this.employees = new Employee[rowCount];
for(int rowIndex = 0;rowIndex < rowCount; rowIndex++)
{
inLine = inReader.readLine();
Scanner employeeScanner = new Scanner(inLine).useDelimiter(",");
String workerType = employeeScanner.next();
String firstName = employeeScanner.next();
String lastName = employeeScanner.next();
String hireDate = employeeScanner.next();
int shift = employeeScanner.nextInt();
if(workerType.substring(0,2).equals("PW"))
{
double pay = employeeScanner.nextDouble();
employees[rowIndex]= new ProductionWorker(workerType, firstName, lastName, hireDate, shift, pay);
}
else if(workerType.substring(0,2).equals("TL"))
{
double pay = employeeScanner.nextDouble();
double bonusRate = employeeScanner.nextDouble();
int reqHours = employeeScanner.nextInt();
int recHours = employeeScanner.nextInt();
employees[rowIndex]= new TeamLeader(workerType, firstName, lastName, hireDate, shift, pay, bonusRate, reqHours, recHours);
}
else if(workerType.substring(0,2).equals("SU"))
{
double salary = employeeScanner.nextDouble();
double bonusRate = employeeScanner.nextDouble();
employees[rowIndex]= new ShiftSupervisor(workerType, firstName, lastName, hireDate, shift, salary, bonusRate );
}
}
return;
}catch(IOException ioe)
{
System.err.print("\nTrouble reading employee file: "+fileName);
}
}
JOptionPane.showMessageDialog(null, "\nFile Name does not exist!\n Process terminating!");
System.exit(0);
}
private String makeEmployeeList(){
StringBuilder sbSU = null;
for(int i=0; i < employees.length; i++)
{
sbSU = new StringBuilder();
if(employees[i].substring(0,2).equals("SU"))
{
sbSU.append(employees[i].toString());
}
}
return sbSU.toString();
}
First of all, you missed a dot after emplyees[i] subsrting
As string is an immutable object, I suggest you use StringBuilder and its append method instead of +=. and use its toString() method to convert StringBuilder to a String. You also need to override your Employees's toString method.
to sort the employees in an array, you need to implements Comparable or Comparator interface so that the Array knows which criteria to use when sorting your employees, in your case it is to compare the employee's type
As you are using JOptionPane you can use html inside to give it format. Make an Employee class and make it's natural order by type, or you can use a Comparator if you don't want to use Comparable
I made a complete example for you.
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;
public class Employee implements Comparable<Employee> {
private String type;
private String name;
public Employee(String type, String name) {
super();
this.type = type;
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
public int compareTo(Employee o) {
if (this.type.equals(o.type)) {
return name.compareTo(o.name);
}
return type.compareTo(o.type);
}
public static void main(String[] args) {
List<Employee> employees = new ArrayList<Employee>();
employees.add(new Employee("CA","John"));
employees.add(new Employee("CA", "Suzy"));
employees.add(new Employee("TA","Malcom"));
employees.add(new Employee("AA","Rose"));
// Sort the list by type as its natural order or use proper Comparator
Collections.sort(employees);
StringBuilder sb = new StringBuilder();
sb.append("<html><table><tr><td>Type</td><td>Name</td></tr>");
for (Employee e : employees) {
sb.append("<tr>");
sb.append("<td> ").append(e.getType()).append("</td>");
sb.append("<td> ").append(e.getName()).append("</td>");
sb.append("</tr>");
}
sb.append("</table></html>");
JOptionPane.showMessageDialog(null, sb);
}
}
Output: