简体   繁体   English

如何不使用collections.sort()按字母顺序对数组列表排序

[英]How to sort an arraylist alphabetically without using collections.sort();

I have the following code, and I have sort the array list alphabetically in the main method, as the user inputs his strings. 我有以下代码,并且在用户输入字符串时,在main方法中按字母顺序对数组列表进行了排序。 Here is my code: 这是我的代码:

import java.util.Scanner;
import java.util.ArrayList;

class Main{
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<String>();
    Scanner scan = new Scanner(System.in);
    String name;
    do{
      System.out.println("Enter the next name: ");
      name = scan.nextLine();
      String toUpperCase = titleCase(name);
      if(!toUpperCase.equals("Stop")){
        names.add(toUpperCase);
      }
    } while(!name.equalsIgnoreCase("STOP"));

    System.out.println(names.toString());


  }
  public static String titleCase(String s){
    String output = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    return output;
  }
}

Please don't give any generic answers, I've been struggling with this for a while now. 请不要给出任何一般性的答案,我已经为此苦苦挣扎了一段时间。 If the answer seems simple to you, it probably isn't for me. 如果答案对您来说似乎很简单,那可能不适合我。

replace this line: 替换此行:

names.add(toUpperCase);

with this: 有了这个:

int index = names.size();
for (int i = 0; i < names.size(); i++) {
    if (names.get(i).compareTo(toUpperCase) > 0) {
        index = i;
        break;
    }
}
names.add(index, toUpperCase);

so, every time you have new string from user - you will insert it into proper position of your array list 因此,每次您从用户那里获得新字符串时,都将其插入到数组列表的正确位置

this method is quite slow, but ok for home assignment 这种方法很慢,但是可以在家分配

As suggested in the comments, the most simple way of maintaining a sorted data structure upon each insert is to use a TreeSet or any other data structure that maintains sorted order internally. 如评论中所建议,在每次插入时维护排序数据结构的最简单方法是使用TreeSet或任何其他内部维护排序顺序的数据结构。 Instead of declaring an ArrayList<String> you would simply need to modify your code to this: 无需声明ArrayList<String> ,只需修改代码即可:

Set<String> names = new TreeSet<>();
Scanner scan = new Scanner(System.in);
String name;
do {
  System.out.println("Enter the next name: ");
  name = scan.nextLine();
  String toUpperCase = titleCase(name);
  if(!toUpperCase.equals("Stop")){
    names.add(toUpperCase);
  }
} while(!name.equalsIgnoreCase("STOP"));

From Javadocs for TreeSet: 从Javadocs for TreeSet:

the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. Set接口是根据equals操作定义的,但是TreeSet实例使用其compareTo(或compare)方法执行所有元素比较,因此从集合的角度来看,此方法认为相等的两个元素相等。 The behavior of a set is well-defined even if its ordering is inconsistent with equals; 即使集合的顺序与equals不一致,它的行为也是明确定义的; it just fails to obey the general contract of the Set interface. 它只是不遵守Set接口的一般约定。

Please try below code. 请尝试以下代码。 You can replace the sorting algorithm with more efficient algorithm like merge sort/selection sort etc.. 您可以将排序算法替换为更有效的算法,例如合并排序/选择排序等。

import java.util.Scanner;
import java.util.ArrayList;

class alsort{
  public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<String>();
    Scanner scan = new Scanner(System.in);
    String name;
    do{
      System.out.println("Enter the next name: ");
      name = scan.nextLine();
      String toUpperCase = titleCase(name);
      if(!toUpperCase.equals("Stop")){
        names.add(toUpperCase);
      }
    } while(!name.equalsIgnoreCase("STOP"));

    System.out.println(names.toString());

    for(int i=0;i<name.length();i++){
        for(int j=i;j<=name.length();j++){
            if(names.get(i).compareTo(names.get(j))>0){
                String tmp=names.get(i);
                names.set(i, names.get(j));
                names.set(j, tmp);
            }
        }
    }

    System.out.println(names.toString());


  }
  public static String titleCase(String s){
    String output = s.substring(0, 1).toUpperCase() + s.substring(1).toLowerCase();
    return output;
  }
}
public class SortedArrayList<T> extends ArrayList<T> {

        /**
     * 
     */
    private static final long serialVersionUID = 1L;


        @SuppressWarnings("unchecked")
        public void insertSorted(T value) {
            add(value);
            Comparable<T> cmp = (Comparable<T>) value;
            for (int i = size()-1; i > 0 && cmp.compareTo(get(i-1)) < 0; i--)
                Collections.swap(this, i, i-1);
        }


    public static void main(String[] s){        
        SortedArrayList<String> myList = new SortedArrayList<String>();

        myList.insertSorted("ddd");   
        myList.insertSorted("aaa");
        myList.insertSorted("xyz"); 
        System.out.println(myList);     
    }



}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM