14.7 集合
集合:集合是存儲對象數據的集合容器。集合比數組的優勢:1.集合可以存儲任意類型的對象數據,數組只能存儲同一種數據類型 的數據。2.集合的長度是會發生變化的,數組的長度是固定的。Collection: 單例集合的 根接口。List: 如果實現了List接口的集合類,具備的特點是:有序,可重復Set:如果實現了Set接口的集合類,具備的特點是:無序,不可重復。Collection 接口 中的方法:boolean add(E,e); 成功返回trueboolean addAll(Collection<? extends E> c) void clear()清空集合中的元素boolean remove(Object o) 從此 collection 中移除指定元素的單個實例,如果存在的話(可選操作)。boolean removeAll(Collection<?> c) 移除此 collection 中那些也包含在指定 collection 中的所有元素(可選操作)。boolean retainAll(Collection<?> c) 僅保留此 collection 中那些也包含在指定 collection 的元素(可選操作)。int size() 返回此 collection 中的元素數。比較重要的boolean isEmpty() 判斷是否為空boolean contains(Object o) 如果此 collection 包含指定的元素,則返回 true。boolean containsAll(Collection<?> c) 如果此 collection 包含指定 collection 中的所有元素,則返回 true。Object[] toArray()?
? ? ? ? ? 返回包含此 collection 中所有元素的數組。? Object[] arr = c.toArray(); //需求: 把編號是110的人信息 輸出。for(int i = 0 ; i<arr.length ; i++){Person p = (Person) arr[i]; //從Object數組中取出的元素只能使用Object類型聲明變量接收,如果需要其他 的類型需要進行強制類型轉換。if(p.id==110){System.out.println(p);}}
@Overridepublic boolean equals(Object obj) {Person p = (Person)obj;return this.id == p.id ;}//java規范: 一般重寫equlas方法我們都會重寫hashCode方法的。@Overridepublic int hashCode() {return this.id;}
? ? ? ? ? 返回包含此 collection 中所有元素的數組。? Object[] arr = c.toArray(); //需求: 把編號是110的人信息 輸出。for(int i = 0 ; i<arr.length ; i++){Person p = (Person) arr[i]; //從Object數組中取出的元素只能使用Object類型聲明變量接收,如果需要其他 的類型需要進行強制類型轉換。if(p.id==110){System.out.println(p);}}
java.util 中接口Collection
注意點:重新toString函數
例如:在對象中重寫
@Overridepublic String toString() {return "{編號:"+this.id+" 姓名:"+ this.name+"}";}@Overridepublic boolean equals(Object obj) {Person p = (Person)obj;return this.id == p.id ;}//java規范: 一般重寫equlas方法我們都會重寫hashCode方法的。@Overridepublic int hashCode() {return this.id;}
總結
- 上一篇: 14.6 设置后台线程
- 下一篇: 15.1 集合的迭代器