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());
}
}
Related
This question already has answers here:
Why is each public class in a separate file?
(11 answers)
Closed 3 years ago.
I am using Eclipse to run this code program to test a Person class and its subclasses. In Eclipse it shows there are errors--that each child class must be defined in its own file.
I am learning Java, and would like to know if this is a must? Or can I make it work with parent and child classes all in one file? If I'm missing something, please point me in the right direction. Thank you!
Here is my code: [I put this is all in one file on Eclipse]
import java.util.*;
//Test program to test Person class and its subclasses
public class Test {
public static void main(String[] args) {
Person person = new Person("person");
Student student = new Student ("student");
Employee employee = new Employee("employee");
Faculty faculty = new Faculty("faculty");
Staff staff = new Staff("staff");
//invoke toString() methods
System.out.println(person.toString());
System.out.println(student.toString());
System.out.println(employee.toString());
System.out.println(faculty.toString());
System.out.println(staff.toString());
}
}
//Defining class Person
public class Person {
protected String name;
protected String address;
protected String phoneNum;
protected String email;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress () {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNum() {
return phoneNum;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public String getEmail() {
return email;
}
public void setEmail (String email) {
this.email = email;
}
#Override
public String toString() {
return "Name:"+getName()+"Class:"+this.getClass().getName();
}
}
//Defines class Student extends Person
public class Student extends Person {
public static final String FRESHMAN = "freshman";
public static final String SOPHMORE = "sophmore";
public static final String JUNIOR = "junior";
public static final String SENIOR = "senior";
protected String classStatus;
public Student(String name) {
super(name);
}
public Student(String name, String classStatus) {
super(name);
this.classStatus = classStatus;
}
#Override
public String toString() {
return "Name:"+getName()+"Class:"+this.getClass().getName();
}
}
//Defines class Employee extends Person
public class Employee extends Person {
protected double salary;
protected String office;
protected MyDate dateHired;
public Employee(String name) {
this(name, 0, "none", new MyDate());
}
public Employee(String name, double salary, String office, MyDate dateHired) {
super(name);
this.salary = salary;
this.office = office;
this.dateHired - dateHired;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getOffice() {
return office;
}
public void setOffice (String office) {
this.office = office;
}
public MyDate getDateHired() {
return dateHired;
}
public void setDateHired(MyDate dateHired) {
this.dateHired = dateHired;
}
#Override
public String toString() {
return "Name:"+getName()+"Class:" + this.getClass().getName();
}
}
//Defines class Faculty extends Employee
public class Faculty extends Employee {
public static String LECTURER = "lecturer";
public static String ASSISTANT_PROFESSOR = "assistant professor";
public static String ASSOCIATE_PROFESSOR + "associate professor";
public static PROFESSOR = "professor";
protected String officeHours;
protected String rank;
public Faculty(String name) {
this(name, "9-5 PM", "Employee");
}
public Faculty(String name, String officeHours, String rank) {
super(name);
this.officeHours = officeHours;
this.rank = rank;
}
public String getOfficeHours() {
return officeHours;
}
public void setOfficeHours(String officeHours) {
this.officeHours = officeHours;
}
public String getRank() {
return rank;
}
public void setRank(String rank) {
this.rank=rank;
}
#Override
public String toString() {
return "Name:"+getName()+"Class:"+this.getClass().getName();
}
}
//Defines class Staff extends Employee
public class Staff extends Employee {
protected String title;
public Staff(String name) {
this(name, "none");
}
public Staff(String name, String title) {
super(name);
this.title=title;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return "Name:"+getName()+"Class:"+this.getClass().getName();
}
}
//Define class MyDate
public class MyDate {
private int month, day, year;
public MyDate (int month, int day, int year) {
this.day=day;
this.month=month;
this.year=year;
}
}
Yes, there should be one class per file. Moreover, you are using the MyDate class in the Employee class, which you need to extend and you cannot extends more than one class, so it's better use the predefined Date class which is present java.util.Date. Import this in the Employee class.
import java.util.Date;
instead of this:
public Employee(String name, double salary, String office, MyDate dateHired)
use:
public Employee(String name, double salary, String office, Date dateHired)
There are some careless mistakes:
in Employee class
public static String ASSOCIATE_PROFESSOR + "associate professor";
change to:
public static String ASSOCIATE_PROFESSOR = "associate professor";
Similarly in faculty class
public static String ASSOCIATE_PROFESSOR + "associate professor";
put = instead of +.
Now this code will work.
Yes it is a must. One class per file. Class can have inner classes. You can define subclasses as inner classes. But I recommend putting them in separate files and don't use inner classes.
I have a java class like :
public class Sclass {
private Student student;
private Teacher teacher;
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
public class Teacher {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Student {
private String name;
private 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;
}
}
I want to use Sclass in a rest service and thus want a json for the same, please assist.
Example using gson:
Student student = new Student();
student.setName("Student 1");
student.setAge(18);
Teacher teacher = new Teacher();
teacher.setName("Teacher 1");
Sclass sclass = new Sclass();
sclass.setStudent(student);
sclass.setTeacher(teacher);
Gson gson = new Gson();
String json = gson.toJson(sclass);
System.out.println(json);
Output:
{"student":{"name":"Student 1","age":18},"teacher":{"name":"Teacher 1"}}
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());
}
}
}
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();
}
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;
}
}}