so I have a problem with my generics code. I've created class Person and Student extends Person. When I was trying to compare both students it suddenly perceived it as a Person and group number wasn't even included. Here is my Person class
public class Person implements Comparable<Person>{...
public int compareTo(Person o) {
if(this.name.compareTo(o.name) > 0 )
return 1;
else if(this.name.compareTo(o.name) < 0)
return -1;
else{
if(this.age > o.age)
return 1;
else if(this.age < o.age)
return -1;
else{
return 0;}
}
}
My Student, where compareTo seems quite similar but with additional group id
public class Student extends Person implements Comparable<Person>{
public int compareTo(Student s) {
if(this.name.compareTo(s.name) > 0 ){
System.out.println(this + " > " + s);
return 1;}
else if(this.name.compareTo(s.name) < 0){
System.out.println(this + " < " + s);
return -1;}
else{
if(this.age > s.age){
System.out.println(this + " > " + s);
return 1;}
else if(this.age < s.age){
System.out.println(this + " < " + s);
return -1;}
else{
if(groupId > s.groupId){
System.out.println(this + " > " + s);
return 1;
}
else if(groupId < s.groupId){
System.out.println(this + " < " + s);
return -1;}
else{
System.out.println(this + " = " + s);
return 0;}
}
}
}
And finally a Box class that is using generics to find maximum and minimum of these classes and other types.
public class Box<T extends Comparable> extends ArrayList<T> {
public T min() {
T t = get(0);
for(int i = 0; i < this.size(); i++){
if(t.compareTo(get(i)) > 0)
t = super.get(i);
}
return t;
}
}
I haven't shown you entire code, but I think it is enough. I've made Box object and still it is comparing them as Person not as Students. Can someone explain what is the problem here? Edit: my Array
Box<Student> bst = new Box<>();
bst.add(new Student("Nowacka", 24, 100));
bst.add(new Student("Nowacka", 24, 300));
bst.add(new Student("Nowacka", 24, 200));
bst.print();
System.out.println(bst.max()); // Student: Nowacka, 24, 300
the answer should be 300, yet is 100 and in Person's compareTo i've added earliel some System.out.println to see which method it is using