How to iterate the arraylist of diffrent objects - java

In an ArrayList I have two different objects,
Student and Employee. I want to iterate through them one by one. I am able to iterate through the list and use the Employee objects but not the Student objects.
I have the following code:
package javaCollections;
import java.util.ArrayList;
import java.util.Iterator;
class Employee {
#Override
public String toString() {
return "employee [name=" + name + ", age=" + age + "]";
}
public String name;
public int 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;
}
Employee(String name, int age) {
this.age = age;
this.name = name;
}
}
class Student {
#Override
public String toString() {
return "student [stud_name=" + stud_name + ", rollNumber=" + rollNumber
+ "]";
}
String stud_name;
int rollNumber;
public Student(String stud_name, int rollNumber) {
super();
this.stud_name = stud_name;
this.rollNumber = rollNumber;
}
public String getStud_name() {
return stud_name;
}
public void setStud_name(String stud_name) {
this.stud_name = stud_name;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
}
public class Arraylist {
ArrayList<Object> emparray;
public void addemp() {
Employee emp = new Employee("abc", 12);
emparray = new ArrayList<Object>();
emparray.add(emp);
Employee emp1 = new Employee("def", 12);
emparray.add(emp1);
Student std = new Student("efg", 123);
Student std1 = new Student("xyz", 123);
emparray.add(std);
emparray.add(std1);
}
public void iterateemp() {
/*
* Iterator<Object> itr=emparray.iterator();
*
* while(itr.hasNext()) { System.out.println(itr.next()); }
*/
for (Object e : emparray) {
System.out.println(((Employee) e).getAge());
System.out.println(((Employee) e).getName());
}
}
public static void main(String[] args) {
Arraylist al = new arraylist();
al.addemp();
al.iterateemp();
}
}
can someone please help me on this?

What you need to do is check the instance of the object.
for (Object e : emparray) {
if(e instanceof employee) {
System.out.println(((employee) e).getAge());
System.out.println(((employee) e).getName());
} else if(e instanceof student) {
// do something else
}
}
}
IMO this is a bad design.

The best practice is to create common base called Person that has shared fields like name. Then you can replace Object with Person in the loop.
import java.util.ArrayList;
import java.util.Iterator;
interface Person{
public String getName();
public void setName(String name);
}
class employee implements Person{
#Override
public String toString() {
return "employee [name=" + name + ", age=" + age + "]";
}
public String name;
public int 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;
}
employee(String name, int age) {
this.age = age;
this.name = name;
}
}
class student implements Person{
#Override
public String toString() {
return "student [stud_name=" + name + ", rollNumber=" + rollNumber
+ "]";
}
String name;
int rollNumber;
public student(String stud_name, int rollNumber) {
super();
this.name = stud_name;
this.rollNumber = rollNumber;
}
public int getRollNumber() {
return rollNumber;
}
public void setRollNumber(int rollNumber) {
this.rollNumber = rollNumber;
}
#Override
public String getName() {
return name;
}
#Override
public void setName(String name) {
this.name=name;
}
}
public class arraylist {
ArrayList<Person> emparray;
public void addemp() {
employee emp = new employee("abc", 12);
emparray = new ArrayList<Person>();
emparray.add(emp);
employee emp1 = new employee("def", 12);
emparray.add(emp1);
student std = new student("efg", 123);
student std1 = new student("xyz", 123);
emparray.add(std);
emparray.add(std1);
}
public void iterateemp() {
for (Person e : emparray) {
if (e instanceof employee) {
System.out.println(((employee) e).getAge());
}else{
/// do for student
}
System.out.println(e.getName());
}
}
public static void main(String[] args) {
arraylist al = new arraylist();
al.addemp();
al.iterateemp();
}
}

for (Object e : emparray) {
if(e instanceof employee) {
System.out.println(((employee) e).getAge());
System.out.println(((employee) e).getName());
} else if(e instanceof student) {
System.out.println(((student) e).getRollNumber());
System.out.println(((student) e).getStud_name());
}
}
}

Related

Is there any way to change values for created user from MainClass?

I can't change values for the object which I created in Main class.
It uses java jre 8. I've tried it on eclipse IDE.
import java.util.HashMap;
public class Main {
public static HashMap<String,Data> PlayerData = new HashMap<String,Data>();
public static void main(String[] args) {
PlayerData.put("User1", new Data("User1","Password1",21));
PlayerData.get("User1").giveInformation();
PlayerData.get("User1").setAge(78);
try{
PlayerData.get("User1").giveInformation();
}catch(NullPointerException e) {
System.out.println("Error!");
}catch(Exception e) {
System.out.println("Error!");
}
}
}
class Data {
private String Name;
private String Password;
private int Age;
public Data(String Name, String Password, int Age) {
this.setName(Name);
this.setPassword(Password);
this.setAge(Age);
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getPassword() {
return Password;
}
public void setPassword(String password) {
Password = password;
}
public int getAge() {
return Age;
}
public void setAge(int age) {
Age = age;
}
public void giveInformation() {
System.out.println("Name: " + this.Name);
System.out.println("Password: " + this.Password);
System.out.println("Age: " + this.Age);
}
}
I wanted to run giveInformation() method to see changed calues but I don't know how to do it.

Collections.sort() Method not working

While sorting an arraylist of Customer Class(user defined) having name and age as attributes on the basis of name, Collections.sort() method is showing error that "the type java.util.Comparator is not resolved.it is indirectly referenced from required .class file.
package comparable;
import java.util.*;
public class Tester {
public static void main(String[] args){
List<Customer> custtlist=new ArrayList<Customer>();
Customer c1=new Customer("vikas",1);
Customer c2=new Customer("mittal",2);
custtlist.add(c1);
custtlist.add(c2);
System.out.println("Before Sorting");
Iterator<Customer> iterator = custtlist.iterator();
while(iterator.hasNext()){
Customer customer = (Customer) iterator.next();
System.out.println(customer.getCustname());
}
Collections.sort(custtlist);
System.out.println("After Sorting");
iterator = custList.iterator();
while (iterator.hasNext()) {
Customer customer = (Customer) iterator.next();
System.out.println(customer.getCustName());
}
}
}
//Customer Class
package comparable;
public class Customer implements Comparable<Customer> {
private String custname;
private int age;
public Customer(String custname, int age) {
this.custname = custname;
this.age = age;
}
public Customer() {
}
public String getCustname() {
return custname;
}
public void setCustname(String custname) {
this.custname = custname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int compareTo(Customer c){
return this.custname.compareTo(c.getCustname());
}
}
You have an awful lot of typos in the code. After I corrected them, the compilation was successful. I took the liberty to make some improvements and styling.
import java.util.*;
public class Tester {
public static void main(String[] args){
List<Customer> customersList = new ArrayList<Customer>();
Customer c1 = new Customer("vikas", 1);
Customer c2 = new Customer("mittal", 2);
customersList.add(c1);
customersList.add(c2);
System.out.println("Before Sorting");
for(Customer customer : customersList) {
System.out.println(customer.getName());
}
Collections.sort(customersList);
System.out.println("\nAfter Sorting");
for(Customer customer : customersList) {
System.out.println(customer.getName());
}
}
}
public class Customer implements Comparable<Customer> {
private String name;
private int age;
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
public Customer() {
}
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 int compareTo(Customer c){
return this.name.compareTo(c.getName());
}
}

implementation of inheritance in arraylist

addEmployee – This method will take Employee reference as parameter and add the same to the employees list after checking if employee with same id does not exist. It will return total employees count if addition is successful, else return -1.
public class Employee {
private int empId;
private String name;
private double basicPay;
private double perksPay;
public Employee()
{
}
public Employee(int empId, String name, double basicPay, double perksPay) {
super();
this.empId = empId;
this.name = name;
this.basicPay = basicPay;
this.perksPay = perksPay;
}
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBasicPay() {
return basicPay;
}
public void setBasicPay(double basicPay) {
this.basicPay = basicPay;
}
public double getPerksPay() {
return perksPay;
}
public void setPerksPay(double perksPay) {
this.perksPay = perksPay;
}
public class Organization extends Employee
{
ArrayList<Employee> emp=new ArrayList<Employee>();
public int addEmployee(Employee e)
{
.......
}
}
The old java way:
public int addEmployee(Employee e) {
for (Employee employee : emp) {
if (e.getId() == employee.getId()) {
return -1;
}
}
emp.add(e);
return emp.size();
}
EDIT:
The Java8 way:
public int addEmployee(Employee e) {
List<Employee> alreadyInList = emp.stream().filter(em -> em.getId() == e.getId()).collect(Collectors.toList());
return alreadyInList.isEmpty() ? -1 : alreadyInList.size();
}

Deserialize yaml to list of objects

Say I have a Yaml file like this,
people:
- name : Joe
surname : Barber
age : 16
- name : Andy
surname : Lots
age : 17
And I have a class like this,
public class people {
private String name;
private String surname;
private String age;
<!-- With getters and setters -->
}
How would i go about getting a list of people objects from the Yaml file?
Just getting the value from a key in the file is fairly simple but mapping it to a collection of objects is not.
I am using the snakeYaml lib.
i hope this can help you.
public class StackOverflow {
public static void main(String[] args) {
final URL resource = StackOverflow.class.getResource("people.yaml");
final Constructor peopleContructor = new Constructor(Group.class);
final TypeDescription peopleDescription = new TypeDescription(People.class);
peopleDescription.putMapPropertyType("people", People.class, Object.class);
peopleContructor.addTypeDescription(peopleDescription);
final Yaml yaml = new Yaml(peopleContructor);
try {
final Group group = (Group) yaml.load(resource.openStream());
for (final People people : group.getPeople()) {
System.out.println(people);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static class People {
private String name;
private String surname;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "People: {name: " + this.name + ", surname: " + this.surname + ", age: " + this.age + "}";
}
}
public static class Group {
private List<People> people;
public List<People> getPeople() {
return people;
}
public void setPeople(List<People> people) {
this.people = people;
}
}}

sorting an arrayList<class> by its integer contents

I am passing an arrayList to a method to sort its data.
The data in the arrayList would contain multiple id numbers correlating to different students.
the array will also include other information. How do i sort the arrayList by its id #. I believe it will have to do with my created class which is included below
more code can be provided as necessary
public static class Student {
public String firstName;
public String lastName;
public Integer uid;
public StudentType type;
public Student(Student orig) {
this.firstName = orig.firstName;
this.lastName = orig.lastName;
this.uid = orig.uid;
this.type = orig.type;
}
// construct a new student with given fields
public Student(String firstName, String lastName, Integer newUid, StudentType type) {
this.firstName = firstName;
this.lastName = lastName;
this.uid = newUid;
this.type = type;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return lastName;
}
//set type
public void setType(StudentType type) {
this.type = type;
}
//return type
public StudentType getType() {
return type;
}
public void setUid(Integer uid){
this.uid = uid;
}
public Integer getUid() {
return uid;
}
// return a string representation of the invoking object
public String toString() {
return firstName + " " + lastName + " " + uid + " " + type;
}
public static class Graduate extends Student {
public boolean thesis;
public ClassStanding study;
public String profName;
public Graduate(Student orig, boolean isThesis, ClassStanding study, String profName) {
super(orig);
thesis = isThesis;
this.study = study;
this.profName = profName;
}
public boolean getThesis() {
return thesis;
}
public void setThesis(Boolean thesis) {
this.thesis = thesis;
}
public ClassStanding getStudy() {
return study;
}
public void setStudy(ClassStanding study) {
this.study = study;
}
public String getProfName() {
return profName;
}
public void setProfName(String profName) {
this.profName = profName;
}
public String toString() {
return super.toString() + thesis + " " + study + " " + profName;
}
}
public static class UnderGraduate extends Student {
public Major major;
public Double overallGpa;
public Double majorGpa;
public ClassStanding study;
public UnderGraduate(Student orig, Major major, Double overallGpa, Double majorGpa, ClassStanding study) {
super(orig);
this.study = study;
this.major = major;
this.overallGpa = overallGpa;
this.majorGpa = majorGpa;
}
public void setMajor(Major major) {
this.major = major;
}
//return type
public Major getmMajor() {
return major;
}
public void setOverallGPA(Double overallGpa) {
this.overallGpa = overallGpa;
}
public Double getOverallGPA() {
return overallGpa;
}
public void setMajorGPA(Double majorGpa) {
this.majorGpa = majorGpa;
}
public Double getMajorGPA() {
return majorGpa;
}
public ClassStanding getStudy() {
return study;
}
public void setStudy(ClassStanding study) {
this.study = study;
}
public String toString() {
return study + " " + major + " " + overallGpa + " " + majorGpa;
}
}
}
Collections.sort(myListofStudents, new Comparator<Student>() {
#Override
public int compareTo(Student s1, Student s2) {
return s1.getUid().compareTo(s2.getUid());
}
});
Alternatively, you can have Student implement Comparable<Student>, which means including a .compareTo().
NB: If you're going to override .compareTo(), you should override .equals(), which means you should override hashCode().
Define a Comparator<Student> and use it with Collections.sort:
public class StudentComparator implements Comparator<Student> {
#Override
public int compare (Student s1, Student s2) {
// Your comparison logic here
}
}
...then...
Collections.sort(data, new StudentComparator());
See the JavaDoc on Comparator for more information.
Create a Comparator for Student, then use Collections.sort()

Categories