Colletions工具类
概念:集合工具类,定义了除了存取以外的集合常用方法。
方法:
public static void reverse(List
<?> list
)
public static void shuffle(List
<?> list
)
public static void sort(List
<T> list
)
使用参考
import java
.util
.*
;
public class Demo04 {
public static void main(String
[] args
) {
List
<Integer> list
= new ArrayList<>();
list
.add(20);
list
.add(2);
list
.add(60);
list
.add(0);
list
.add(26);
System
.out
.println("排序之前:" + list
.toString());
Collections
.sort(list
);
System
.out
.println("排序之后:" + list
.toString());
int i
= Collections
.binarySearch(list
, 26);
System
.out
.println(i
);
List
<Integer> dest
= new ArrayList<>();
for (int j
= 0; j
< list
.size(); j
++) {
dest
.add(0);
}
Collections
.copy(dest
, list
);
System
.out
.println("复制后dest:" + dest
.toString());
Collections
.reverse(list
);
System
.out
.println("反转之后:" + list
);
Collections
.shuffle(list
);
System
.out
.println("打乱之后:" + list
);
System
.out
.println("------list转为数组------");
Integer
[] arr
= list
.toArray(new Integer[0]);
Integer
[] arr1
= list
.toArray(new Integer[10]);
System
.out
.println(arr
.length
);
System
.out
.println(Arrays
.toString(arr
));
System
.out
.println(arr1
.length
);
System
.out
.println("超过所给元素:" + Arrays
.toString(arr1
));
System
.out
.println("------数组转成集合------");
String
[] names
= {"赵", "钱", "孙", "李", "周", "吴"};
List
<String> list1
= Arrays
.asList(names
);
System
.out
.println(list1
);
Integer
[] nums
= {100, 300, 500, 700, 900};
List
<Integer> list2
= Arrays
.asList(nums
);
System
.out
.println(list2
);
}
}
总结
集合的概念:对象的容器,和数组类似,定义了对多个对象进行操作的常用方法,只能存储引用型数据。List集合:有序、有下标、元素可重复。(ArrayList(数组)、LinkedList(双向链表)、Vector)Set集合:无序、无下标、元素不可重复。(HashSet(哈希表:数组+链表+红黑树)、TreeSet(红黑树))Map集合:存储一对数据,无序、无下标,键不可重复,值可重复。(HashMap(哈希表)、HashTable、TreeMap(红黑树))Collections:集合工具类,定义了除了存储以外的集合常用的方法。