集合类
为什么会出现集合类
面向对象语言对事物的体现都是以对象的形式,所以为了方便对较多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方式
数组和集合类同时容器,有何不同?
数组虽然也可以存储对象,但是长度不可变;集合的长度是可变的,数组中可以存储基本数据类型,集合只能存储对象。
集合类的特点:
集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象。
为什么会出现这么多的容器呢?
因为每一个容器对数据的存储方式都有不同
这个存储方式称之为:数据结构
共性方法:(Collection 的方法)
增、删、改、查。
|
方法摘要 |
||
|
boolean |
||
|
boolean |
addAll(Collection<? extends E> c) |
|
|
void |
clear() |
|
|
boolean |
||
|
boolean |
containsAll(Collection<?> c) |
|
|
boolean |
||
|
int |
hashCode() |
|
|
boolean |
isEmpty() |
|
|
iterator() |
||
|
boolean |
||
|
boolean |
removeAll(Collection<?> c) |
|
|
boolean |
retainAll(Collection<?> c) |
|
|
int |
size() |
|
|
Object[] |
toArray() |
|
|
toArray(T[] a) |
|
add 方法的参数类型是Object 以便于接收任意类型的对象
集合中存储的都是对象的引用(地址)
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
//method_1();
method_2();
}
public static void method_2() {
ArrayList al1 = new ArrayList();
ArrayList al2 = new ArrayList();
al1.add("abc01");
al1.add("abc02");
al1.add("abc03");
al1.add("abc04");
al2.add("abc01");
al2.add("abc02");
al2.add("abc05");
al2.add("abc06");
al1.removeAll(al2);//去除al1与al2的交集,保存在al1中
sop(al1);
sop(al2);
/*
* 打印结果:
* [abc03, abc04]
*
* [abc01, abc02, abc05, abc06]
*
* */
}
public static void method_1() {
// 创建一个集合容器,使用Collection接口的子类ArrayList
ArrayList a1 = new ArrayList();
// 添加元素
a1.add("abc01");
a1.add("abc02");
a1.add("abc03");
a1.add("abc04");
// 获取个数 集合长度
System.out.println(a1.size());
// 打印集合
System.out.println(a1);
// 删除元素
a1.remove("abc03");
System.out.println(a1);
/*
* 打印结果 4 [abc01, abc02, abc03, abc04] [abc01, abc02, abc04]
*/
// a1.clear();//清空集合
// 判断某一元素是否在集合中
System.out.println(a1.contains("abc01"));
// 判断集合是否为空
System.out.println(a1.isEmpty());
}
public static void sop(Object obj) {
System.out.println(obj);
}
}原文地址:http://blog.csdn.net/u013476556/article/details/44832019