Storing a collection of objects on an Arraylist - java

I am trying to store a collection of objects on the list employ. But I am getting an error on employ.addAll(), I have tried to employ.add() but I still get the error.
import java.util.ArrayList;
public class Employee {
public String FullName;
public float wage;
public int ID;
ArrayList<Employee> employ = new ArrayList<Employee>();
Employee(String name, float wage, int ID){
this.FullName = name;
this.wage = wage;
this.ID = ID;
}
Employee e = new Employee("Tony", 1245, 2222);
employ.addAll(e); //here is where I a getting the error
}

You are adding a single Employee, so use add, not addAll :
Employee e = new Employee("Tony", 1245, 2222);
employ.add(e);
Beside that, employ.add(e); should be inside some method.

employ.addAll() expects a collection, for adding single element use employ.add().
import java.util.ArrayList;
public class Employee {
public String FullName;
public float wage;
public int ID;
Employee(String name, float wage, int ID){
this.FullName = name;
this.wage = wage;
this.ID = ID;
}
public static void main(String[] args) {
ArrayList<Employee> employ = new ArrayList<Employee>();
Employee e = new Employee("Tony", 1245, 2222);
employ.add(e);
}
}

Related

Using getters to access Arraylist field of Arraylist

I'm using a comparator to evaluate the equivalency of 2 objects that are in ArrayLists. When I try to get the field values of the ArrayList (Services) of the ArrayList (Transactions) with getters from the targeted ArrayList for the getters that I'm trying to use to access the fields in Service class. I have the getters for Service class created but im not sure how to properly access the field from twice removed ArrayLists.
This is in the customer class
ArrayList<Service> services = chckedTransaction.getServices(getServiceName, getPrice, getMechanics);
CUSTOMER CLASS
public class Customer {
private String name;
private String address;
private int phoneNumber;
private ArrayList<Transaction> transactioins;
private ArrayList<Car> cars;
public Customer(String name, String address, int phoneNumber, String carMake,
String carModel, int manufactureYear) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.transactioins = new ArrayList<Transaction>();
this.cars = new ArrayList<Car>();
createNewCar(carMake, carModel, manufactureYear);
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public int getPhoneNumber() {
return phoneNumber;
}
public ArrayList<Transaction> getTransactioins() {
return transactioins;
}
public ArrayList<Car> getCars() {
return cars;
}
private Transaction findTransaction(ServiceType serviceName, double price, Employee mechanic){
ServiceComperator comperator = new ServiceComperator();
Service dummyService = createDummyService(serviceName, price);
for(int i=0; i<this.transactioins.size(); i++){
Transaction chckedTransaction = this.transactioins.get(i);
ArrayList<Service> services = chckedTransaction.getServices(getServiceName, getPrice, getMechanics);
for(Service currentService : services){
if(comperator.compare(dummyService, chckedTransaction.getServices())){
}
}
}
private Service createDummyService(ServiceType serviceName, double price){
Service dummyServices = new Service(serviceName, price);
return dummyServices;
}
TRANSACTIONS CLASS
public class Transaction {
private ArrayList<Service> services;
public Transaction() {
this.services = new ArrayList<Service>();
}
public ArrayList<Service> getServices() {
return services;
}
SERVICE CLASS
public class Service {
private ServiceType serviceName;
private double price; //might need to use a link list double
private ArrayList<Employee> machanics;
public Service(ServiceType serviceName, double price) {
this.serviceName = serviceName;
this.price = price;
this.machanics = new ArrayList<Employee>();
}
public ServiceType getServiceName() {
return serviceName;
}
public double getPrice() {
return price;
}
public ArrayList<Employee> getMachanics() {
return machanics;
}
public void addEmployee(String mechanicName){
machanics.add(new Employee(mechanicName));
}
Turns out I just had some missing parameters for the create and find methods.
Thanks, guys for pointing out the missing parameters. I made the changes and now it compiles just fine.
Customer class
public boolean createNewTransaction(ServiceType serviceName, double price,
Employee mechanic, String mechanicName){
Transaction existingTransaction = findTransaction(serviceName, price, mechanic);
if(existingTransaction == null){
Transaction newTransaction = new Transaction();
newTransaction.createNewService(serviceName, price, mechanic, mechanicName);
this.transactioins.add(newTransaction);
}
return false;
}
private Transaction findTransaction(ServiceType serviceName, double price, Employee mechanic){
ServiceComperator comperator = new ServiceComperator();
Service dummyService = createDummyService(serviceName, price);
for(int i=0; i<this.transactioins.size(); i++){
Transaction chckedTransaction = this.transactioins.get(i);
ArrayList<Service> services = chckedTransaction.getServices();//.getSericeName();
for(Service currentService : services){
if(comperator.compare(dummyService, currentService) == 0){
return this.transactioins.get(i); // not sure if this is correct or not
}
}
}return null;
}

I need to get the max from a Employee class from a Farm class

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).

Class Level Variable Eligible for GC in Java

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.

Java: Storing an Array into an Array?

Is it possible to store three string values added into an array (studentName), and store that into a different array so it can be found later?
Basically my main goal is to store a name, user id, and a balance (fullName, idName, 300).
And add that into a "super(?)" array so when people type down, it finds the fullName and pulls the information from there.
You can create a class
public class Student {
private String name;
private String id;
private int balance;
}
and then you can create a list of these objects:
List<Student> list = new ArrayList<Student>();
Map<String, String> map = new HashMap<String, String>();
then:
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
and then:
map.put("name", "Thomas");
map.put("id", "Thomas id");
map.put("balance", ""300);
listOfMaps.add(map);
Anyhow, be careful. You will have to keep numbers (f.e. balance) as a String and after you will need to map it.
Well, I believe you are talking about something like Jagged Array which is available in C# but for java, we can do it in some other ways... like creating a class and manipulating it as Generic List implementation...
public class Student {
private String name;
private int id;
private int balanace;
public Student(){}
public Student(String name, int id, int balance){
this.name = name;
this.id = id;
this.balanace = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBalanace() {
return balanace;
}
public void setBalanace(int balanace) {
this.balanace = balanace;
}
}
In some other class where you would want to manipulate
public class ManipulateData {
public static void main(String[] args){
Student student1 = new Student("James", 1, 500);
List<Student> list = new ArrayList<Student>();
list.add(student1);
for(Student s: list){
System.out.println("Name : " + s.getName());
System.out.println("ID : " + s.getId());
System.out.println("Balance : " + s.getBalanace());
}
}
}

showing null pointer exception with junit test case

i am trying to sort the employee object based on salary using the junit test case.
it is my employee sort class
package day4;
import day4.Employee;
public class EmployeesInfoWithSalary {
private Employee[] employee;
private int numberOfEmployees;
public EmployeesInfoWithSalary(Employee[] employee, int numberOfEmployees) {
super();
this.employee = employee;
this.numberOfEmployees = numberOfEmployees;
}
public Employee[] getSortBasedOnSalary() {
String temp;
for (int iterator = 0; iterator < numberOfEmployees; iterator++) {
int minSalary = employee[iterator].getSalary();
int index = iterator;
for (int comparator = iterator; comparator < numberOfEmployees; comparator++) {
if (employee[comparator].getSalary() < minSalary) {
index = comparator;
minSalary = employee[comparator].getSalary();
}
}
employee[index].setSalary(employee[iterator].getSalary());
employee[iterator].setSalary(minSalary);
temp = employee[index].getId();
employee[index].setId(employee[iterator].getId());
employee[iterator].setId(temp);
temp = employee[index].getName();
employee[index].setName(employee[iterator].getName());
employee[iterator].setName(temp);
}
return employee;
}
}
employee object class is as follows
package day4;
public class Employee {
private String id;
private String name;
private int salary;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
}
testemployee salary class for junit test case is as follows
package day4;
import static org.junit.Assert.*;
import day4.Employee;
import org.junit.Test;
public class TestEmployeeInfoWithSalary {
#Test
public void testGetSortBasedOnSalary() {
Employee[] employee = new Employee[5];
employee[0].setName("pratap");
employee[1].setName("aruna");
employee[2].setName("satyam");
employee[3].setName("krishna");
employee[4].setName("siva");
employee[0].setId("k0100");
employee[1].setId("k0101");
employee[2].setId("k0102");
employee[3].setId("k0103");
employee[4].setId("k0104");
employee[0].setSalary(10000);
employee[1].setSalary(1000);
employee[2].setSalary(8000);
employee[3].setSalary(6000);
employee[4].setSalary(9000);
EmployeesInfoWithSalary employeeInfoWithSalary= new EmployeesInfoWithSalary(employee, 5);
employee[4].setName("pratap");
employee[0].setName("aruna");
employee[2].setName("satyam");
employee[1].setName("krishna");
employee[3].setName("siva");
employee[4].setId("k0100");
employee[0].setId("k0101");
employee[2].setId("k0102");
employee[1].setId("k0103");
employee[3].setId("k0104");
employee[4].setSalary(10000);
employee[0].setSalary(1000);
employee[2].setSalary(8000);
employee[1].setSalary(6000);
employee[3].setSalary(9000);
assertArrayEquals(employee,employeeInfoWithSalary.getSortBasedOnSalary());
}
}
the log is showing the error that null point expression..
can any body help me..
thanks..
I suspect this is the line of the NPE.
// creates an array full of null values.
Employee[] employee = new Employee[5];
employee[0].setName("pratap");
You need to add Employee objects to each element in the array.
A better approach is to use a constructor which takes all the needed fields.
Employee[] employee = {
new Employee("pratap", "k0100", 10000),
new Employee("aruna", "k0101", 1000),
new Employee("satyam", "k0102", 8000),
new Employee("krishna","k0103", 6000),
new Employee("siva", "k0104", 9000) };
After
Employee[] employee = new Employee[5];
for each index in array you need to initialize Employee object.
employee[0] = new Employee(); etc

Categories

Resources