我想根据他们的掷骰号码对学生进行排序。我知道如何使用合并排序对整数的arraylist进行排序,但是对Student类型的ArrayList进行排序是不同的。
我的Student类包含以下属性:
public static class Student
{
String name;
int rollNum, WebMark, dsMark, dmMark;
public Student(String name, int rollNum, int WebMark, int dsMark, int dmMark)
{
this.name = name;
this.rollNum = rollNum;
this.WebMark = WebMark;
this.dsMark = dsMark;
this.dmMark = dmMark;
}
}
我见过人们使用Comparators对对象属性的ArrayLists进行排序。但是,他们将它用于内置排序,如下面一行(这很简单):
Collections.sort(Database.arrayList, new CustomComparator());
但是,我想使用我在Student课程中编写的mergesort函数。但是我仍然不明白我将如何将属性'rollNum'传递给mergesort函数以及如何相应地移动ArrayList中的其他属性?我从来没有在谷歌的任何地方见过这个。
这是我的完整代码:
package student;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Comparator;
public class Main
{
public static class Student
{
String name;
int rollNum, WebMark, dsMark, dmMark;
public Student(String name, int rollNum, int WebMark, int dsMark, int dmMark)
{
this.name = name;
this.rollNum = rollNum;
this.WebMark = WebMark;
this.dsMark = dsMark;
this.dmMark = dmMark;
}
public String getName()
{
return name;
}
public int getRollNum()
{
return rollNum;
}
public int getWebMark()
{
return WebMark;
}
public int getDSMark()
{
return dsMark;
}
public int getDMMark()
{
return dmMark;
}
public static void addStudent(ArrayList<Student> studentArray)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter Name: ");
String name = input.next();
System.out.println("Enter Roll Number");
int rollNum = input.nextInt();
System.out.println("Enter Web Mark:");
int webMark = input.nextInt();
System.out.println("Enter Data Structure Mark:");
int DSMark = input.nextInt();
System.out.println("Enter Discrete Math Mark:");
int DMMark = input.nextInt();
//create this student profile in array
Student newStudent = new Student(name,rollNum,webMark,DSMark,DMMark);
studentArray.add(newStudent);
}
public static void findStudent(int rollNum, ArrayList<Student> studentArr)
{
for(int i = 0; i < studentArr.size(); i++)
{
if(studentArr.get(i).getRollNum()==rollNum)
{
System.out.println("Roll Number: " + studentArr.get(i).getRollNum() +
", Name: " + studentArr.get(i).getName() +
", Web Grade: " + studentArr.get(i).getWebMark() +
", Data Structure Grade: " + studentArr.get(i).getDSMark() +
", Discrete Math Grade: " + studentArr.get(i).getDMMark());
}
else
{
System.out.println("Couldn't find student.");
}
}
}
public static void deleteStudent(ArrayList<Student> studentArr)
{
System.out.println("Enter Student Roll Number: ");
Scanner input = new Scanner(System.in);
int rollNum = input.nextInt();
for(int counter = 0; counter < studentArr.size(); counter++)
{
if(studentArr.get(counter).getRollNum() == rollNum)
{
studentArr.remove(counter);
}
}
}
public String toString()
{
return name + " " + rollNum + " " + WebMark + " " + dsMark + " " + dmMark;
}
public static double avg(ArrayList<Student> studentArr)
{
double[] avgArr = new double[studentArr.size()];
double max = 0.0;
for(int counter = 0; counter < studentArr.size(); counter++)
{
avgArr[counter] = (studentArr.get(counter).getWebMark() +
studentArr.get(counter).getDSMark() + studentArr.get(counter).getDMMark())/(3);
if(avgArr[counter] > max)
{
max = avgArr[counter];
}
}
return max;
}
public int compareTo(Student studCompare)
{
int compareRollNum = ((Student) studCompare).getRollNum();
//ascending order
return this.rollNum - compareRollNum;
}
/*Comparator for sorting the array by student name*/
public static Comparator<Student> StuNameComparator = new Comparator<Student>()
{
public int compare(Student s1, Student s2)
{
String StudentName1 = s1.getName().toUpperCase();
String StudentName2 = s2.getName().toUpperCase();
//ascending order
return StudentName1.compareTo(StudentName2);
//descending order
//return StudentName2.compareTo(StudentName1);
}
};
/*Comparator for sorting the array by student name*/
public static Comparator<Student> StuRollno = new Comparator<Student>()
{
public int compare(Student s1, Student s2)
{
int rollno1 = s1.getRollNum();
int rollno2 = s2.getRollNum();
//ascending order
return rollno1-rollno2;
//descending order
//return StudentName2.compareTo(StudentName1);
}
};
public static <T extends Comparable<T>> List<T> mergeSort(List<T> m)
{
// exception
if (m==null) throw new NoSuchElementException("List is null");
// base case
if (m.size() <= 1) return m;
// make lists
List<T> left = new ArrayList<>();
List<T> right = new ArrayList<>();
// get middle
int middle = m.size()/2;
// fill left list
for (int i = 0; i < middle; i++)
{
if (m.get(i)!=null) left.add(m.get(i));
}
// fill right list
for (int i = middle; i < m.size(); i++)
{
if (m.get(i)!=null) right.add(m.get(i));
}
// recurse
left = mergeSort(left);
right = mergeSort(right);
// merge
return merge(left,right);
}
private static <T extends Comparable<T>> List<T> merge(List<T> left, List<T> right)
{
List<T> result = new ArrayList<>();
// merge
while (!left.isEmpty() && !right.isEmpty())
{
if (left.get(0).compareTo(right.get(0)) <= 0)
{
result.add(left.remove(0));
}
else
{
result.add(right.remove(0));
}
}
// cleanup leftovers
while (!left.isEmpty())
{
result.add(left.remove(0));
}
while (!right.isEmpty())
{
result.add(right.remove(0));
}
return result;
}
}
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int userChoice = 0;
int userChoice2 = 0;
ArrayList<Student> studentArr = new ArrayList<Student>(); //array size is 6
System.out.println("1- Merge Sort");
System.out.println("2- Shell Sort");
System.out.println("3- Quit");
userChoice2 = input.nextInt();
if (userChoice2 == 1 || userChoice2 == 2)
{
do {
System.out.println("1- Add a New Record");
System.out.println("2- Sort by Student Name");
System.out.println("3- Sort by Roll Number");
System.out.println("4- Delete a Student Specific Record");
System.out.println("5- Display a Student Specific Record");
System.out.println("6- Search");
System.out.println("7- Display the Highest Average");
System.out.println("8- Print"); //print the array size, sort time, and number of comparisons to the screen.
System.out.println("9- Quit");
System.out.println("Select your Option: \n");
userChoice = input.nextInt();
switch (userChoice) {
case 1:
Student.addStudent(studentArr);
break;
case 2:
if (userChoice2 == 1) {
//call mergesort function
} else if (userChoice2 == 2) {
//call shell sort function
}
case 3:
if (userChoice2 == 1) {
//call mergesort function
} else if (userChoice2 == 2) {
//call shell sort function
}
case 4:
Student.deleteStudent(studentArr);
break;
case 5:
System.out.println("Enter Student Roll Number: ");
int rollNum_ = input.nextInt();
Student.findStudent(rollNum_, studentArr);
break;
case 6:
case 7:
double highestAvg = Student.avg(studentArr);
System.out.println("Highest Average is: " + highestAvg);
break;
case 8:
System.out.println("Printing students...");
System.out.print(studentArr);
System.out.println("\n");
break;
case 9:
}
} while (userChoice != 9);
}
else
{
return;
}
input.close();
}
}
答案 0 :(得分:1)
您的Student
已经Comparable
且已经与使用Student
字段的其他rollNum
个实例进行比较,因此当前实现使用{{ 1}}应该已经对该字段进行排序。
但是如果你想使用不同的排序进行排序,你可以写一个compareTo()
并改变你的排序方法,如下所示:
Comparator
此处,您不需要private static <T> List<T> merge(List<T> left, List<T> right, Comparator<? super T> comparator) {
.. use comparator.compare(a, b) instead of a.compareTo(b)
}
限制T
。
答案 1 :(得分:0)
为了对任何东西进行排序,该对象必须具有可比性。在java中,有两种方法可以为对象(如student)执行此操作: 可比较和比较。
话虽这么说,你的对象必须实现Comparable接口然后编写必要方法compareTo的实现,在那里列出你希望如何相互比较。
另一种方法是实现Comparator接口并为compare方法编写实现。
完成后,您可以使用Collection.sort .....方法对集合进行排序。