集合是java中提供的一種容器,能夠用來存儲多個數據。java
集合和數組都是元素,他們的區別:數組
數組的長度是固定的。集合的長度是可變的。集合中存儲的元素必須是引用類型數據。spa
使用ArrayList集合存儲元素並遍歷的過程:code
public static void main(String[] args) { ArrayList<Double> arr1=new ArrayList<Double>(); arr1.add(1.6); arr1.add(2.3); arr1.add(3.6); for(int i=0;i<arr1.size();i++){ System.out.print(arr1.get(i)+" "); }
//集合存儲引用數據類型 ArrayList<Person> arr2=new ArrayList<Person>(); arr2.add(new Person("張三",18)); arr2.add(new Person("小紅帽",8)); arr2.add(new Person("大灰狼",55)); for(int i=0;i<arr2.size();i++){ System.out.println(arr2.get(i)); }
集合的繼承實現關係:對象
Collection接口經常使用的子接口有:List接口、Set接口blog
List接口經常使用的子類有:ArrayList類、LinkedList類繼承
Set接口經常使用的子類有:HashSet類、LinkedHashSet類接口
記住下面這張圖:rem
其中list容許有重複元素,且是有序。set中不容許有重複元素,且爲無序。get
Collection接口的基本方法
建立集合的格式:
方式1:Collection<元素類型> 變量名 = new ArrayList<元素類型>();(通常經常使用的)
方式2:Collection 變量名 = new ArrayList();
//建立Collection對象 Collection<String> col=new ArrayList<String>(); //添加元素 //add(E e)方法,E表明建立集合時所指定的數據類型如<String>,那麼,E就表明String類型;建立集合時若沒有指定數據類型,那麼,E就表明Object類型。 col.add("中國"); col.add("你好"); col.add("java");
//判斷集合中是否包含某元素,返回值爲布爾值 boolean flag=col.contains("java"); System.out.println(flag);
//移除集合中的元素 ,返回值爲布爾值 boolean obj=col.remove("你好"); System.out.println(obj);
//清除集合中的內容 //col.clear();
//將集合轉爲數組 // 數組轉型時 不能直接強轉 須要對數組中的元素遍歷 強轉 Object[] obj1=col.toArray(); //遍歷數組 for(int i=0;i<obj1.length;i++){ System.out.println(obj1[i]); } //遍歷集合 ArrayList<String> arr=null; if(col instanceof ArrayList){ arr=(ArrayList<String>)col; } for(int i=0;i<arr.size();i++){ System.out.println(arr.get(i)); }