Java Collection 集合体系的使用
package com. zhong. collection ; import java. util. ArrayList ;
import java. util. Arrays ;
import java. util. Collection ;
import java. util. HashSet ; public class CollectionDemo { public static void main ( String [ ] args) { System . out. println ( "-------------ArrayList 有序 可重复 有索引-------------" ) ; ArrayList < String > arr = new ArrayList < > ( ) ; arr. add ( "1" ) ; arr. add ( "2" ) ; arr. add ( "3" ) ; System . out. println ( arr. get ( 1 ) ) ; System . out. println ( arr) ; System . out. println ( "-------------HashSet 无序 不重复 无索引-------------" ) ; HashSet < String > hashArr = new HashSet < > ( ) ; hashArr. add ( "1" ) ; hashArr. add ( "3" ) ; hashArr. add ( "2" ) ; hashArr. add ( "2" ) ; hashArr. add ( "3" ) ; System . out. println ( hashArr) ; Collection < String > collection = new ArrayList < > ( ) ; System . out. println ( "-------------添加元素-------------" ) ; collection. add ( "123" ) ; collection. add ( "abc" ) ; collection. add ( "张三" ) ; System . out. println ( collection) ; System . out. println ( "-------------清空集合-------------" ) ; collection. clear ( ) ; System . out. println ( collection) ; System . out. println ( "-------------判断集合是否为空-------------" ) ; boolean empty = collection. isEmpty ( ) ; System . out. println ( empty) ; collection. add ( "111" ) ; collection. add ( "222" ) ; collection. add ( "333" ) ; System . out. println ( collection. isEmpty ( ) ) ; System . out. println ( "-------------获取集合的长度-------------" ) ; int size = collection. size ( ) ; System . out. println ( size) ; System . out. println ( "-------------判断集合包含某个元素-------------" ) ; boolean contains = collection. contains ( "222" ) ; System . out. println ( contains) ; System . out. println ( collection. contains ( "444" ) ) ; System . out. println ( "-------------删除集合中的某个元素 如果有多个先删除左边的第一个-------------" ) ; System . out. println ( contains) ; collection. remove ( "222" ) ; System . out. println ( contains) ; System . out. println ( "-------------集合转换为数组-------------" ) ; Object [ ] array = collection. toArray ( ) ; System . out. println ( Arrays . toString ( array) ) ; String [ ] array1 = collection. toArray ( new String [ collection. size ( ) ] ) ; System . out. println ( Arrays . toString ( array1) ) ; }
}