I need to find and display the the employee who has the maximum salary from the Farm.
this is what I got so far
public class Employee implements Comparable<Employee> {
private String name;
private Integer salary;
public Employee (String name , Integer salary) {
this.name = name;
this.salary = salary;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
public Integer getSalary() {
return salary;
}
public String toString() {
return name + " " + salary;
}
public int compareTo(Employee emp) {
return this.salary.compareTo(emp.getSalary());
}
}
Employee class
public class Farm {
private String name;
private Integer surface;
List<Employee> emp = new ArrayList<Employee>();
public Farm(String name , Integer surface) {
this.name = name;
this.surface = surface;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setSurface(Integer surface) {
this.surface = surface;
}
public int getSurface () {
return surface;
}
public String toString() {
return name + " " + surface;
}
public void makeList(String ename , Integer esalary) {
this.emp.add(new Employee(ename,esalary));
}
public void getList() {
for(Employee el : emp)
System.out.println(el);
}
}
And the last one is the main. The thing is that I don't know how can I have more farms and get the max from every single one of them. Can you guys help me?
And this is my mainapp
public class Mainapp {
public static void main(String args[])
{
List <Farm> FarmList = new ArrayList<Farm>();
FarmList.add(new Farm("unirea pizdii", 890030));
FarmList.add(new Farm("pseudo autsm",78594));
FarmList.add(new Farm("haha hihi",854856099));
Farm farm1 = new Farm("Tiguana" , 700);
farm1.makeList("Mihai", 30000);
farm1.makeList("Vladimir", 4000);
farm1.makeList("Tusnic", 3000);
farm1.getList();
Employee emp1 = new Employee(" mihai", 3000);
System.out.println(emp1);
}
}
To get employee with max salary for each farm you can use stream api:
import static java.util.stream.Collectors.*;
Map<Farm, Optional<Employee>> collect =
farmList.stream().collect(groupingBy(Function.identity(),
flatMapping(farm -> farm.getEmployes().stream(),
maxBy(Employee::compareTo))));
Result map has Farm as a key and Employee with max salary as a value
Note: flatMapping method is from java9
There are multiple ways to sort a List in Java, one of them being Collections.sort(List), but in this case it looks like you are trying to retrieve the maximum value from the list, so there's no need to add the extra overhead.
EDIT: JB Nizet suggested using Collections.max(List):
public Employee getMostPaidEmployee() {
return Collections.max(emp);
}
One way to get the most paid employee from the list would be to loop through them and compare each one to the previously "saved" most paid employee:
// Farm.java
public Employee getMostPaidEmployee() {
Employee mostPaid = null;
// Initialize maximum to the lowest possible value.
// If salaries can only be positive you could also initialize this to `0`.
int maximumSalary = Integer.MIN_VALUE;
for (Employee employee : emp) {
if (employee.getSalary() > maximumSalary) {
// Reset the most paid fields
mostPaid = employee;
maximumSalary = employee.getSalary();
}
}
return mostPaid;
}
You can declare this method on the Farm class, so you will be able to call it even if you have multiple instances of Farm:
List<Farm> farms = new ArrayList<>();
// TODO Add farms
// Get the most paid employee in first farm
Employee mostPaid = farms.get(0).getMostPaidEmployee();
In terms of performance, this method is linear, i.e. O(n).
Inheritance is not completely working for me as the extra variables outside the inheritance class are not being displayed. When I input the employee details and input the wage it is accepted. But then it is not shown when I list all employees in database or when searching for an employee
public class Employee extends Person {
public Employee(){ }
public Employee (int id, int wage, String name, String surname){
super(id,name,surname);
this.wage = wage;
}
private int wage;
public void SetWage(int wg){
wage=wg;
}
public int GetWage (){
return wage;
}
public String toString(){
return "ID: " + this.GetId() + "\n"
+ "Name:" + this.GetName() + "\n"
+ "Surname:" + this.GetSurname() + "\n"
+ "Wage: " + this.GetWage();
}
}
Similarly the client class is not working. Also here is the code for the person class
public class Person{
public Person(){
pId = 0;
pName = "";
pSurname = "";
}
public Person (int id, String nm, String sn) {
pId = id;
pName = nm;
pSurname = sn;
}
private int pId;
private String pName;
private String pSurname;
public int GetId(){
return pId;
}
public void SetId(int id){
pId= id;
}
public String GetName(){
return pName;
}
public void SetName(String nm){
pName = nm;
}
public String GetSurname (){
return pSurname;
}
public void SetSurname(String sn){
pSurname = sn ;
}
public String ToString(){
return "ID: " + this.GetId() + "\n"
+ "Name:" + this.GetName() + "\n"
+ "Surname:" + this.GetSurname();
}
}
Any suggestions?
First of all, order your class as follows: fields, constructors, methods. Try not to have constructors before the fields, it's rather hard to read.
Also, just like paisanco noted out in the comments - try to ask more specific questions, it's not easy to understand what is the problem.
Last thing - if I understand right, you probably can't access Person class fields, such as:
private int pId;
private String pName;
private String pSurname;
This is most likely problem of how you create your object.
Instead of
Emplyee emp = new Employee();
Try creating employee object in such manner:
Person pers = new Employee();
This should fix this and you should be able to access person class fields aswell.
And if you after that would like to access employee fields like wage and so on, you should cast the object to Employee object, e.g:
if (pers instanceof Employee) {
((Employee) pers).getWage();
}
If you are trying to use it in the following way:
Person employee = new Employee()
you will not be able to use SetWage and GetWage functions because they are not part of Person object. If you want to use work that way you can declare them as abstract functions in Person class of instantiate your object differently: Employee employee = new Employee()
Hi I have written this program that Implements a superclass Employee that has the following fields and methods.
Fields:
String firstName
String lastName
int employeeID
double salary
Methods:
Constructor(): initialize balance field to null and zero.
Setters and getters for firstName, lastName, and employeeID
EmployeeSummary() – prints all account attributes
Part 2: Implement a Manager class that inherits from the Employee class.
Has a department attribute
Methods:
EmployeeSummary() – prints all superclass and subclass attributes
The problem is I expected to see:
Employee Name: Charles Dickens Employee Id : 34599 salary: 6500.0
Department : Accounts
as the output but I get nothing....
Any help is greatly appreciated.
here is the code:
package week1john_huber;
import java.util.*;
import java.lang.*;
import java.io.*;
class Employee {
//attributes of Employee class
private String firstName;
private String lastName;
private int employeeID;
private double salary;
public Employee() { //default constructor
firstName = null;
lastName = null;
employeeID = 0;
salary = 0.0;
}
public void setFirstName(String fname) { //set and get methods for all attributes
firstName = fname;
}
public String getFirstname() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lname) {
lastName = lname;
}
public double getEmployeeID() {
return employeeID;
}
public void setEmployeeID(int empId) {
employeeID = empId;
}
public double getSalary() {
return salary;
}
public void setSalary(double s) {
salary = s;
}
public void EmployeeSummary() { //display all attributes of Employee
System.out.println("Employee Name: " + firstName + " " + lastName + " Employee Id :" + employeeID + " salary: " + salary);
}
}
class Manager extends Employee {
private String department;
public Manager() { //default constructor
super(); //calling superor base class default constructor
department = null;
}
public String getDepartment() {
return department;
}
public void setDepartment(String dept) { //set and get methods for department
department = dept;
}
public void EmployeeSummary() {
super.EmployeeSummary(); //calling super class method with same name
System.out.println("Department : " + department);
}
}
class TestEmployee {
public static void main(String[] args) {
Manager mgr = new Manager();
mgr.setFirstName("Charles"); //all set methods of super class are available to derived class
mgr.setLastName("Dickens");
mgr.setEmployeeID(34599);
mgr.setSalary(6500);
mgr.setDepartment("Accounts");
mgr.EmployeeSummary();
}
}
Ok, I believe the problem is the fact that you have the whole thing in a single file.
Try moving the TestEmployee class to its own file and rename the class to
public class TestEmployee
It should work that way.
I have an Employee, an Organization and Test class. The employee contains information related to Employee and Organization class contains Employee list. Please find below source code of both class:
Employee.java
package com.practice;
public class Employee {
private String empId;
private String name;
private int age;
private float salary;
public Employee(final String empId, final String name, final int age, final float salary) {
this.empId = empId;
this.name = name;
this.age = age;
this.salary = salary;
}
public String getEmpId() {
return empId;
}
public void setEmpId(final String empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(final float salary) {
this.salary = salary;
}
#Override
public String toString() {
// TODO Auto-generated method stub
return this.empId + " " + this.name + " " + this.age + " " + this.salary;
}
}
Organization.java
package com.practice;
import java.util.ArrayList;
import java.util.List;
public class Organization {
private final List<Employee> empList = new ArrayList<Employee>();
Organization() {
}
public void addEmployee(final Employee emp) {
this.empList.add(emp);
}
public List<Employee> getEmpList() {
return empList;
}
}
TestGC.java
package com.practice;
public class TestGC {
public static void main(final String[] args) {
final Employee emp = new Employee("E1", "Emp 1", 20, 2000.0f);
final Employee emp2 = new Employee("E1", "Emp 1", 20, 2000.0f);
final Organization org = new Organization();
org.addEmployee(emp);
org.addEmployee(emp2);
System.out.println(org.getEmpList());
}
}
In Organization.java, we have list of Employee object and I have created the object in the same line, that means at class level. So, my question is, will that list be eligible for GC once I'm done with Organization object or it will be a leak in memory? Also, will it make any difference if I instantiate the same object inside constructor?
What you have are regular instance variables (as well as a few local variables). They will be collected normally, when they're no longer reachable. It makes no difference if you instantiate them from the constructors, it'll only add unnecessary code.
It's not that easy to leak memory in Java.
Will that list be eligible for GC once I'm done with Organization
object or it will be a leak in memory?
Yes. List will be eligible for the GC once organization object goes out of scope. All you are using are instance variables, so no need to worry about memory leak unless you have some static variables used in bad way.
will it make any difference if I instantiate the same object inside
constructor?
No.
I have created a (Person,Student,Employee,Faculty and Staff)classes. Person has to subclasses Student and Employee.
Employee has two subclasses Faculty and Staff. I have done all the codings an they are working fine except my driver class TestPerson program its giving compilation errors
Note: A test program that Creates a Person,Student,Employee,Faculty,Staff, and invokes their toString Method.
The errors of driver class TestPerson.java are below:-
error: constructor Student in class Student cannot be applied to given types;
error: no suitable constructor found for Employee(String,String,String,String)
error: constructor Faculty in class Faculty cannot be applied to given types;
error: no suitable constructor found for Staff(String,String,String,String)"
**I am just providing the codes of the driver class. If you need my other codings of the other classes, please state in the comment, and I will immediately post it.
Please see my codings below:-
public class TestPerson {
public static void main(String[] args) {
Person person = new Person("John Doe", "123 Somewhere", "415-555-1212", "johndoe#somewhere.com");
Person student = new Student("Mary Jane", "555 School Street", "650-555-1212", "mj#abc.com", "junior");
Person employee = new Employee("Tom Jones", "777 B Street", "40-88-889-999", "tj#xyz.com");
Person faculty = new Faculty("Jill Johnson", "999 Park Ave", "92-52-22-3-333", "jj#abcxyz.com");
Person staff = new Staff("Jack Box", "21 Jump Street", "707-21-2112", "jib#jack.com");
System.out.println(person.toString() + "\n");
System.out.println(student.toString() + "\n");
System.out.println(employee.toString() + "\n");
System.out.println(faculty.toString() + "\n");
System.out.println(staff.toString() + "\n");
}
}
//Person Class
public class Person {
private String name;
private String address;
private String phone_number;
private String email_address;
public Person() {
}
public Person(String newName, String newAddress, String newPhone_number, String newEmail){
name = newName;
address = newAddress;
phone_number = newPhone_number;
email_address = newEmail;
}
public void setName(String newName){
name = newName;
}
public String getName(){
return name;
}
public void setAddress(String newAddress){
address = newAddress;
}
public String getAddress(){
return address;
}
public void setPhone(String newPhone_number){
phone_number = newPhone_number;
}
public String getPhone(){
return phone_number;
}
public void setEmail(String newEmail){
email_address = newEmail;
}
public String getEmail(){
return email_address;
}
public String toString(){
return "Name :"+getName();
}
}
//Student class
public class Student extends Person {
public final String class_status;
public Student(String name, String address, int phone, String email, String classStatus) {
super(name, address, phone, email);
class_status = classStatus;
}
public String toString(){
return "Student Status: " + super.getName();
}
}
//Employee Class
import java.util.Date;
public class Employee extends Person{
private String office;
private double salary;
private Date hire;
public Employee() {
}
public Employee(String name, String address, int phone, String email){
super(name, address, phone, email);
}
public Employee(String office, double salary, Date hire){
this.office = office;
this.salary = salary;
this.hire = hire;
}
public void setOffice(String office){
this.office = office;
}
public String getOffice(){
return this.office;
}
public void setSalary(double salary){
this.salary = salary;
}
public double getSalary(){
return this.salary;
}
public void setHire(Date hire){
this.hire = hire;
}
public Date getHire(){
return this.hire;
}
public String toString(){
return "Office " + super.getName();
}
}
//Faculty Class
public class Faculty extends Employee {
private String officeHours;
private int rank;
public Faculty(String name, String address, int phone, String email) {
super(name, address, phone, email);
}
public String toString(){
return "Office " + super.getOffice();
}
}
//Staff Class
public class Staff extends Employee {
private String title;
public Staff(String name, String address, int phone, String email) {
super(name, address, phone, email);
}
public Staff(String title){
this.title = title;
}
public void setTitle(String title){
this.title = title;
}
public String getTitle(){
return this.title;
}
public String toString(){
return "Title :" + super.getName();
}
}
The reason you are getting those errors is that the constructors don't exist.
error: constructor Student in class Student cannot be applied to given
types; error: no suitable constructor found for
Employee(String,String,String,String)
That means you will not get the code to compile until you have this:
Student(String name, String addr, String phone, String email) {
....
}
Assuming you have set the properties in the constructor, toString would look like this:
public String toString() {
return this.name + "\n" + this.addr + "\n" + this.phone + "\n" + this.email;
}
UPDATE
Your problem is that Student has only this constructor:
public Student(String name, String address, int phone, String email, String classStatus)
Student needs a constructor which takes only four strings as its parameters. Alternatively, you can make everything take the five parameters you specified.
It's perhaps not related to the question itself, but I think the design could be refined like this:
define abstract class Role with the name of role
define classes Student, Employee, Staff whatever inheriting Role
define class Person with common properties for all person type, names etc, and having property of type Role inside
then define toString on Person and in all Role implementation
in this way you will be able to extend or modify Persons independently from Roles, which makes the design more flexible
The constructor of Person requires a String as third argument, but you are trying to pass int phone to the super-constructor in your sub-classes. That won't work because it's the wrong type.
By the way: you should always represent phone numbers with strings, not with integers.
It doesn't make sense to add or subtract phone numbers.
Integers don't allow leading zeros, which are used for area codes in some
countries.
Integers can't be larger than 2147483648. When you
try to store very long telephone numbers, this seemingly arbitrary
limit will cause very unexpected bugs.
First Set the Phone Number datatype as integer in all the classes ..
main Function will be:
public class TestPerson {
public static void main(String[] args) {
Person person = new Person("John Doe", "123 Somewhere", "415-555-1212",
"johndoe#somewhere.com");
Person student = new Student("Mary Jane", "555 School Street",
650-555-1212, "mj#abc.com", "junior");
Person employee = new Employee("Tom Jones", "777 B Street",
40-88-889-999, "tj#xyz.com");
Person faculty = new Faculty("Jill Johnson", "999 Park Ave",
92-52-22-3-333, "jj#abcxyz.com");
Person staff = new Staff("Jack Box", "21 Jump Street", 707-21-2112,
"jib#jack.com");
System.out.println(person.toString() + "\n");
System.out.println(student.toString() + "\n");
System.out.println(employee.toString() + "\n");
System.out.println(faculty.toString() + "\n");
System.out.println(staff.toString() + "\n");
}
}