工具类Collections的使用
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; public class CollectionsDemos { public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<String> al = new ArrayList<String>(); //调用自定义方法向集合中添加元素 addElements(al);// System.out.println(al);//[afgd, dfdf, cc, kkk, kkk] //调用方法对集合内的元素进行排序 Collections.sort(al); System.out.println(al);//[afgd, cc, dfdf, kkk, kkk] //调用自定义比较器进行比较,依据字符串的长度对其进行比较 Collections.sort(al, new MyComparaLength()); System.out.println(al);//[cc, kkk, kkk, afgd, dfdf] } private static void addElements(ArrayList<String> al) { // 向容器中添加元素 al.add("afgd"); al.add("dfdf"); al.add("cc"); al.add("kkk"); al.add("kkk"); } } //自定义一个比较器,以字符串的长度为标准进行比较 class MyComparaLength implements Comparator<String> { @Override public int compare(String o1, String o2) { // TODO Auto-generated method stub int num = o1.length()-o2.length(); if(num==0) return o1.compareTo(o2); return num; } }
运行程序:
//获取集合中最长的元素 String max = Collections.max(al,new MyComparaLength()); System.out.println("集合中最长的元素是:"+max);
运行程序
TreeSet 集合的演示
import java.util.Collections; import java.util.Comparator; import java.util.TreeSet; public class CollectionsDemo2 { public static void main(String[] args) { // TODO Auto-generated method stub TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder()); ts = new TreeSet<String>(Collections.reverseOrder(new MyComparaLength())); ts.add( "abc"); ts.add( "hahaha"); ts.add( "zzz"); ts.add( "aa"); ts.add( "cba"); System.out.println(ts);//[hahaha, zzz, cba, abc, aa] } } class MyComparaLength implements Comparator<String> { @Override public int compare(String o1, String o2) { // TODO Auto-generated method stub int num = o1.length()-o2.length(); if(num==0) return o1.compareTo(o2); return num; } }
运行程序:
ArrayList集合的演示
import java.util.ArrayList; import java.util.Collections; public class ArrayListDemos2 { public static void main(String[] args) { // TODO Auto-generated method stub ArrayList<String> a = new ArrayList<String>(); a.add( "abc"); a.add( "hahaha"); a.add( "zzz"); a.add( "aa"); a.add( "cba"); System.out.println(a);//[abc, hahaha, zzz, aa, cba] Collections.replaceAll(a, "aa", "5555"); System.out.println(a);//[abc, hahaha, zzz, 5555, cba] } }
运行程序:
ArrayList<String> a = new ArrayList<String>(); a.add( "abc"); a.add( "hahaha"); a.add( "zzz"); a.add( "aa"); a.add( "cba"); System.out.println(a);//[abc, hahaha, zzz, aa, cba] Collections.replaceAll(a, "aa", "5555"); System.out.println(a);//[abc, hahaha, zzz, 5555, cba] //对集合中元素的位置进行随机置换 Collections.shuffle(a); System.out.println(a);//[5555, cba, abc, hahaha, zzz]
时间: 2024-10-05 17:17:57