1.Collections.sort方法(以及自定义的比较字符串长度排序)
package Collections; import java.util.*; class StrLenComparator implements Comparator<String>{ public int compare(String s1, String s2) { if(s1.length()>s2.length()){ return 1; } if(s1.length()<s2.length()){ return -1; } return s1.compareTo(s2); } } public class CollectionsDemo1 { public static void main(String[] args) { // TODO Auto-generated method stub List<String> list = new ArrayList(); list.add("wsqdef"); list.add("hue"); list.add("as"); list.add("ao"); list.add("aaaii"); sop(list); //Collections的sort提供了排序的方法 //Collections.sort(list); //自定义的排序方式:按照字符串的长度 Collections.sort(list,new StrLenComparator()); sop(list); } public static void sop(Object obj){ System.out.println(obj+","); } }
Coolections中的方法:
- sort()排序
- reverse()反转
- replace()替换指定元素
- fill()替换全部元素
- binaeySearch()查找角标
- max()查找最大值
- shuffle()随机排列
- swap()固定位置交换元素顺序
方法代码示例:
package Collections; import java.util.*; class StrLenComparator implements Comparator<String>{ public int compare(String s1, String s2) { if(s1.length()>s2.length()){ return 1; } if(s1.length()<s2.length()){ return -1; } return s1.compareTo(s2); } } public class CollectionsDemo1 { public static void main(String[] args) { // TODO Auto-generated method stub reverseDemo(); } public static void reverseDemo(){ List<String> list = new ArrayList(); list.add("wsqdef"); list.add("hue"); list.add("as"); list.add("ao"); list.add("aaaii"); sop(list); //将list的顺序反转 Collections.reverse(list); sop(list); } public static void replaceDemo(){ List<String> list = new ArrayList(); list.add("wsqdef"); list.add("hue"); list.add("as"); list.add("ao"); list.add("aaaii"); sop(list); //将list的指定元素替换成指定的元素 Collections.replaceAll(list, "as", "qq"); sop(list); } public static void fillDemo(){ List<String> list = new ArrayList(); list.add("wsqdef"); list.add("hue"); list.add("as"); list.add("ao"); list.add("aaaii"); sop(list); //将list的中的元素全部替换为pp Collections.fill(list, "pp"); sop(list); } public static void binaeySearchDemo(){ List<String> list = new ArrayList(); list.add("wsqdef"); list.add("hue"); list.add("as"); list.add("ao"); list.add("aaaii"); Collections.sort(list); sop(list); //查找角标 int index = Collections.binarySearch(list, "ao"); sop("index="+index); } public static void maxDemo(){ List<String> list = new ArrayList(); list.add("wsqdef"); list.add("hue"); list.add("as"); list.add("ao"); list.add("aaaii"); Collections.sort(list); sop(list); //查找编码最大的值 String max = Collections.max(list); sop("max="+max); } public static void sortDemo(){ List<String> list = new ArrayList(); list.add("wsqdef"); list.add("hue"); list.add("as"); list.add("ao"); list.add("aaaii"); sop(list); //Collections的sort提供了排序的方法 //Collections.sort(list); //自定义的排序方式:按照字符串的长度 Collections.sort(list,new StrLenComparator()); sop(list); } public static void sop(Object obj){ System.out.println(obj+","); } }