I have been trying to run a stabel sort for the first time. I created an array which has Student Objects. Now i want to sort those objects in that array as per their name alphabetically. What i dont understand is the Arrays.sort(student,new Students()); and what should be its arguments if any. Thanks alot !
import java.util.Comparator;
import java.util.Arrays;
public class Students implements Comparable<Students> {
private String FirstName;
private String lastName;
private int age;
public Students(String firstName, String lastName, int age) {
super();
FirstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int compareTo(Students toCheck) {
int compareQuantity = ((Students)toCheck).getAge();
return this.age-compareQuantity;
}
public static void main(String args[]){
//array for the 6 students
Students[] student= new Students[6] ;
//creating and adding one by one
Students sam = new Students("Sam","Wo", 22 );
student[0]=sam;
Students ben = new Students("Ben","Wang", 27 );
student[1]=ben;
Students arsalan = new Students("Arsalan","Khan", 28);
student[2]=arsalan;
Students issa = new Students("Issa","Hashim", 25 );
student[3]=issa;
//ben khan will test if the last name is different. Should be fun .
Students benK = new Students("Ben","Khan", 29 );
student[4]=benK;
Students jackM = new Students("Jack","Meth", 23);
student[5]=jackM;
Comparator <Students> studentCompare = new Comparator<Students>(){
public int compare (Students s1 , Students s2){
String studentName1 = s1.getFirstName();
String studentName2 = s2.getFirstName();
return studentName1.compareTo(studentName2);
Arrays.sort(student,new Students());
}
}; for(int i =0; i
Arrays.sort()
are stable.Comparator
you're using will only compare the students by first name; is this what you want?