Skip to content

Instantly share code, notes, and snippets.

@helloqiu
Created March 17, 2016 12:23
Show Gist options
  • Save helloqiu/22881a9c955adb0c8914 to your computer and use it in GitHub Desktop.
Save helloqiu/22881a9c955adb0c8914 to your computer and use it in GitHub Desktop.
A Java Example Shown to GuaiSun
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
/**
* Created by helloqiu on 16/3/17.
*/
public class MainClass {
public static void main(String[] args) {
String[] order = {"first","second","third"};
Scanner scanner = new Scanner(System.in);
ArrayList<String> cityArray = new ArrayList<>();
for (int i = 0 ; i < 3 ; i ++) {
System.out.print("Enter the " + order[i] + " city: ");
cityArray.add(scanner.nextLine());
}
Collections.sort(cityArray,new SortCityComparator());
System.out.print("The three cities in alphabetical order are");
for (String string : cityArray) {
System.out.print(" " + string);
}
}
}
import java.util.Comparator;
/**
* Created by helloqiu on 16/3/17.
*/
public class SortCityComparator implements Comparator {
public SortCityComparator() {
super();
}
public int compare(Object x, Object y) {
if (((String)x).charAt(0) < (((String)y).charAt(0))) {
return -1;
}else {
return 1;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment