我有一组电话簿元素,我正在尝试使用可比排序根据字典顺序对它们进行排序。但这一切都一团糟。请帮忙。提前致谢
它也将有助于描述java中的排序功能!这是代码:
package myphonebook;
import javax.swing.*;
import java.util.Arrays;
import java.util.Comparator;
public class MyPhoneBook implements Comparator<MyPhoneBook>{
private String name,email,number;
MyPhoneBook()
{
}
public void input()
{
name = (JOptionPane.showInputDialog("Enter Name:\n")).toString();
number = JOptionPane.showInputDialog("Enter Number:\n").toString();
email = JOptionPane.showInputDialog("Enter email:\n").toString();
}
public void print()
{
JOptionPane.showMessageDialog(null, "Name: " + name+ "\n" + "Phone: " +number +"\n" + "Email: " + email);
}
public static void main(String[] args) {
MyPhoneBook a[] = new MyPhoneBook[300];
MyPhoneBook b = new MyPhoneBook();
//final Integer[] sorted = ArrayUtils.toObject(MyPhoneBook);
int i,n;
n = Integer.parseInt(JOptionPane.showInputDi… total number:\n"));
for(i=0;i<n;i++)
{
a[i] = new MyPhoneBook();
a[i].input();
}
Arrays.sort(a);
for(i=0;i<n;i++)
{
a[i].print();
}
}
@Override
public int compare(MyPhoneBook o1, MyPhoneBook o2) {
return o1.number.compareTo(o2.number);
}
public int compareTo(MyPhoneBook o) {
if(this.name.equals(o.name)) return this.number.compareTo(o.number);
if(this.number.equals(o.number)) return this.email.compareTo(o.email);
if(this.email.equals(o.email)) return this.name.compareTo(o.name);
return 0;
}
}