<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
java collections是什麼,讓我們一起了解一下?
Collections是集合類的一個工具類或幫助類,服務於Java的Collection框架,其中提供了一系列靜態方法,用於對集合中元素進行排序、搜索以及線程安全等各種操作。
Java中Collections有哪些用法?
1、sort(Collection)方法的使用(含義:對集合進行排序)。
示例如下:
public class Practice { public static void main(String[] args){ List c = new ArrayList(); c.add("l"); c.add("o"); c.add("v"); c.add("e"); System.out.println(c); Collections.sort(c); System.out.println(c); } } 運行結果為:[l, o, v, e] [e, l, o, v]
2、reverse()方法的使用(含義:反轉集合中元素的順序)。
示例如下:
public class Practice { public static void main(String[] args){ List list = Arrays.asList("one two three four five six siven".split(" ")); System.out.println(list); Collections.reverse(list); System.out.println(list); } }[one, two, three, four, five, six, siven][siven, six, five, four, three, two, one]
3、shuffle(Collection)方法的使用(含義:對集合進行隨機排序)。
示例如下:
public class Practice { public static void main(String[] args){ List c = new ArrayList(); c.add("l"); c.add("o"); c.add("v"); c.add("e"); System.out.println(c); Collections.shuffle(c); System.out.println(c); Collections.shuffle(c); System.out.println(c); } } 運行結果為:[l, o, v, e] [l, v, e, o] [o, v, e, l]