集合:集合是Java中提供的一种容器,可以用来存储多个数据。
集合与数组都是容器,它们的区别是什么?
1、数组的长度是固定的,集合的长度是可变的。
2、数组中存储的是同一类型的元素,可以存储基本数据类型值。集合存储的都是对象。而且对象的类型可以不同。在开发中,一般当对象多的时候,使用集合进行存储。
集合框架


Collection常用方法
-
-
booleanadd(E e)确保此集合包含指定的元素(可选操作)。booleanaddAll(Collection c)将指定集合中的所有元素添加到此集合(可选操作)。voidclear()从此集合中删除所有元素(可选操作)。booleancontains(Object o)如果此集合包含指定的元素,则返回true。booleancontainsAll(Collection c)如果此集合包含指定集合中的所有元素,则返回true。booleanequals(Object o)将指定的对象与此集合进行比较以获得相等性。inthashCode()返回此集合的哈希码值。booleanisEmpty()如果此集合不包含元素,则返回true。Iteratoriterator()返回此集合中的元素的迭代器。default StreamparallelStream()返回可能并行的Stream与此集合作为其来源。booleanremove(Object o)从该集合中删除指定元素的单个实例(如果存在)(可选操作)。booleanremoveAll(Collection c)删除指定集合中包含的所有此集合的元素(可选操作)。default booleanremoveIf(Predicate filter)删除满足给定谓词的此集合的所有元素。booleanretainAll(Collection c)仅保留此集合中包含在指定集合中的元素(可选操作)。intsize()返回此集合中的元素数。default Spliteratorspliterator()创建一个Spliterator在这个集合中的元素。default Streamstream()返回以此集合作为源的顺序Stream。Object[]toArray()返回一个包含此集合中所有元素的数组。T[]toArray(T[] a)返回包含此集合中所有元素的数组; 返回的数组的运行时类型是指定数组的运行时类型。
-
public class MyCollection {
public static void main(String[] args) {
Collection<String> obj = new ArrayList<String>();
obj.add("111");
obj.add("222");
obj.add("333");
obj.add("444");
System.out.println(obj);
boolean remove = obj.remove("444");
System.out.println(remove);
System.out.println(obj);
boolean contains = obj.contains("222");
System.out.println(contains);
int size = obj.size();
System.out.println(size);
Object[] array = obj.toArray();
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
obj.clear();
System.out.println(obj);
boolean empty = obj.isEmpty();
System.out.println(empty);
}
}