Java基礎之集合(一)
阿新 • • 發佈:2019-02-15
集合的特點:
可以不斷的往集合容器中新增不同型別的資料,但是隻能存放引用型別的資料
boolean add(E e) 新增元素
List list = new ArrayList();
list.add("大神");
list.add("菜鳥");
list.add("abc");
刪除元素:
boolean remove(Object value)
list.remove("大神");
list.remove("菜鳥");
list.remove("abc");
清空集合元素:
void clear();
list.clear();
判斷集合是否為空
boolean isEmpty()
list.isEmpty ();//為空true,不為空false
獲取集合容量/長度
boolean size();
list.size();
判斷一個集合中是否包含某個值
boolean contains(Object obj)//包含為true,不包含為false
判斷一個集合中是否包含另一個集合中的所有元素
boolean containsAll(Collection coll)
將一個集合的所有元素加入到另一個集合物件中
boolean addAll(Collection coll)
刪除兩個集合的交集部分
boolean removeAll(Collection coll)
保留兩個集合的交集部分
boolean retainAll(collection coll)
//建立集合物件
Collection coll = new ArrayList();
//新增一些元素到集合中
//list介面下的集合類都可以儲存有序可重複的元素
coll.add("abc");
coll.add(true);
coll.add(100);
coll.add(3.14);
//遍歷集合物件
1.獲取迭代器物件
Iterator it = coll.iterator();
while(it.hasNext()){
System.out.prinlt(it.next());
}
System.out.println("------------");
//使用for迴圈+迭代器的方式遍歷集合
for(Iterator it = coll.iterator;it.hasNext();){
System.out.println(it.next())
}
/*
* 需求:使用List儲存字串,並去除重複元素,要求在同一個集合中去除。
假如有一個集合,裡面有一些重複的字串。把重複給我去除。
*/
public class ListDemo {
public static void main(String[] args) {
//建立集合物件l1
List l1 = new ArrayList();
l1.add("aaaa");
l1.add("abc");
l1.add("abc");
l1.add("bbbb");
l1.add("aaaa");
l1.add("xyz");
l1.add("xyz");
l1.add("aaaa");
//建立集合物件l2
List l2 = new ArrayList();
Iterator it = l1.iterator();
while(it.hasNext()){
Object obj = it.next();
if(!l2.contains(obj)){
l2.add(obj);
}
}