我是一名业余程序员,我创建了一个程序,其中包含一个包含不同电话簿联系人的数组列表,并且我尝试使用compareTo 方法按字典顺序对数组列表进行排序。我不知道如何正确调用主方法中的方法,以便它正确排序,并且不允许我使用集合排序。谁能帮我吗?
这是我的一些代码:
public class Phonebook implements Comparable<Phonebook> {
private String first, last;
public Contact(String first, String last) {
this.first = first;
this.last= last;
}
public String getFirst() {return first;}
public String getLast() {return last;}
public String toString() {
return first + " " + last;
}
public int compareTo(Phonebook another) {
int a = last.compareTo(another.last);
int b = first.compareTo(another.first);
if (a== 0 && b== 0)
return 0;
if (a == 0 && b!= 0)
return b;
return a;
}
}
public class PhonebookList implements Iterable<Phonebook>{
ArrayList<Phonebook>phonebook;
public PhonebookList() {
}
public PhonebookList(Contact[]contacts) {
phonebook=new ArrayList<>(Arrays.asList(phonebooks));
}
import java.util.*;
public static void main(String[] args) {
// TODO Auto-generated method stub
PhonebookList list= new PhonebookList();
Phonebook ph1= new Phonebook ("Brandon","Johnson");
Phonebook ph2 = new Phonebook ("Samantha","Joseph");
list.add(ph1);
list.add(ph2);
}
最佳答案
如果项目“较大”,则比较方法返回 1;如果它们相等,则返回 0;如果项目“较小”,则比较方法返回 -1。
这应该有效:
int compareTo (PhoneBook o) {
for(int i = 0; i < first.size(); i++) {
if (i >= o.first.size())
return 1;
if ((int)first.charAt(i) > (int)o.first.charAt(i))
return -1;
else if ((int)first.charAt(i) < (int)o.first.charAt(i))
return 1;
}
for(int i = 0; i < last.size(); i++) {
if (i >= o.last.size())
return 1;
if ((int)last.charAt(i) > (int)o.last.charAt(i))
return -1;
else if ((int)last.charAt(i) < (int)o.last.charAt(i))
return 1;
}
return 0;
}
这只是检查 ASCII 值是否更大。 (所有字母必须为小写或大写)
关于java - 如何使用compareTo 方法按字母顺序对字符串ArrayList 进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58212259/