【问题标题】:How do I sort an ArrayList of strings in alpabetical order using a compareTo method?如何使用 compareTo 方法按字母顺序对字符串的 ArrayList 进行排序?
【发布时间】:2019-10-03 04:19:27
【问题描述】:

我是一名业余程序员,我创建了一个程序,其中包含一个包含不同电话簿联系人的数组列表,我正在尝试使用 compareTo 方法按字典顺序对数组列表进行排序。我不知道如何正确调用 main 方法中的方法,以便正确排序,并且不允许使用集合排序。谁能帮帮我?

这是我的一些代码:

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);
}

【问题讨论】:

  • 那么您是否需要在此作业中实现排序算法?
  • @Martin'sRun 不是真的,我的教授只是告诉我们,存储在arraylist 中的名称应该通过 compareTo() 方法按排序顺序存储
  • Comparable 和 compareTo 方法定义了排序,什么更小,什么更大,但是如果要使用 ArrayList,则必须单独进行排序。由于 collections.sort 是不允许的,我假设其他替代方案,如 list.sort 或 stream.sorted 也不允许?
  • @Martin'sRun 是的,他们不是

标签: java arraylist compareto lexicographic


【解决方案1】:

如果项目“更大”,compare to 方法返回 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 值是否更大。 (所有字母必须是小写或大写)

【讨论】:

    猜你喜欢
    • 2020-04-09
    • 1970-01-01
    • 2015-01-03
    • 2016-03-11
    • 2013-09-12
    • 2017-05-22
    • 2012-08-20
    • 2013-09-04
    • 1970-01-01
    相关资源
    最近更新 更多