日期:2014-05-20 浏览次数:20827 次
import java.util.*; public class Test { public static void main(String[] args) { String[] strs = new String[] {"google.cn", "linggui.gov.cn", "baidu.com", "google.com.hk", "zhidao.baidu.com", "google.com", "sina.com", "tw.msn.com"}; Arrays.sort(strs, new Comparator<String>() { public int compare(String str1, String str2) { String[] strs1 = str1.split("\\."); String[] strs2 = str2.split("\\."); reverse(strs1); reverse(strs2); int length = strs1.length < strs2.length ? strs1.length : strs2.length; for (int i = 0; i < length; i++) { int cmp = strs1[i].compareTo(strs2[i]); if (cmp != 0) { return cmp; } } return strs1.length - strs2.length; } private void reverse(String[] strs) { for (int i = 0; i < (strs.length + 1) / 2; i++) { String tmp = strs[i]; strs[i] = strs[strs.length - i - 1]; strs[strs.length - i - 1] = tmp; } } }); for (int i = 0; i < strs.length; i++) { System.out.println(strs[i]); } } }
------解决方案--------------------
简单
String name="zhidao.baidu.com";
String[] splitnames=name.split('.');//用.拆成数组
splitnames=splitnames.reverse(); //反转数组的顺序
这样就反过来了
然后再排序就行了
------解决方案--------------------
我做了一个 不说了上代码 简单易懂
package test; import java.util.Arrays; import org.junit.Test; import serivce.Servce; import dao.LogDao; import dao.LogDaoIml; import entity.Log; public class LogDaoImltest { @Test public void test() { //new Servce().and(); YuMing[] yms = {new YuMing("", "google", "cn"),new YuMing("zhidao", "baidu", "com"),new YuMing("", "baidu", "com")}; Arrays.sort(yms); for(int i=yms.length-1;i>=0;i--) { System.out.println(yms[i]); } } static private class YuMing implements Comparable<YuMing> { public String head; public String center; public String end; public YuMing(String head, String center, String end) { super(); this.head = head; this.center = center; this.end = end; } @Override public int compareTo(YuMing ym) { if(end.compareTo(ym.end) != 0) { return end.compareTo(ym.end); } if(center.compareTo(ym.center) != 0) { return center.compareTo(ym.center); } if(head.compareTo(ym.head) != 0) { head.compareTo(ym.head); } return 0; } @Override public String toString() { if(head.equals("")) { return center+"."+end; } return head+"."+center+"."+end; } } }