集合之工具类Collections
对于集合,不管是Collection,List,Set,或者Map,都可以使用此工具类,开发中通常很少用数组,而对于一些操作,比如反转,排序等等就可以使用此工具类调用方法来实现
常用方法:
1:reverse(Object o):将集合中的元素进行反转,逆序
2:sort(Object o):将集合中的元素按照从小到大排序,此方法使用的前提是集合元素类型一致
3:synchronized(Object o):将线程不安全的转换成线程安全.
1 /** 2 * Collections工具类:可以操作list,set,map 3 * 常用方法: 4 * 1:reverse(Object o):集合元素进行反转 5 * 2:sort():排序 6 * 3:synchronized(Object o):将线程不安全的转换成线程安全 7 * 4: 8 * 9 * 10 */ 11 public class CollectionsTest { 12 @Test 13 public void test(){ 14 List list=new ArrayList(); 15 list.add(123); 16 list.add(456); 17 list.add(789); 18 System.out.println(list); 19 Collections.reverse(list); 20 System.out.println(list); 21 Collections.sort(list); 22 System.out.println(list); 23 Collections.swap(list,1,2); 24 System.out.println(list); 25 Collections.shuffle(list); 26 System.out.println(list); 27 Collections.synchronizedList(list); 28 29 } 30 31 public static void main(String[] args) { 32 List list=new ArrayList(); 33 Scanner scanner=new Scanner(System.in); 34 boolean is=true; 35 while (is) { 36 list.add(scanner.next()); 37 if (list.size()==3){ 38 System.out.println(list); 39 Collections.reverse(list); 40 System.out.println(list); 41 is=false; 42 } 43 44 } 45 } 46 }
浙公网安备 33010602011771号