1.Collection
1.1 Collection 集合概述和使用
单链集合的顶层接口,它表示一组对象,这些对象也称为Collection的元素
JDK 不提供此接口的任何直接实现,它提供更具体的子接口(Set和List)实现
多态方式
/*
创建Collection集合的对象
多态形式
ArrayList()
*/
public class CollectionDemo01 {
public static void main(String[] args) {
//创建Collection集合的对象
Collection<String> ss=new ArrayList<String>();
//添加元素
ss.add("Hello");
ss.add("Java");
//输出集合对象
System.out.println(ss);
}
}
1.2 Collection 集合常用方法
Collection<String> ss = new ArrayList<String>();
// boolean add(E e);添加元素
ss.add("hello");
ss.add("java");
System.out.println(ss);
// 从集合中移除指定元素
System.out.println(ss.remove("hello"));
System.out.println(ss);
// 清空集合中元素
ss.clear();
System.out.println(ss);
// 判断集合中是否存在指定元素
System.out.println(ss.contains("java"));
//判断集合是否为空
System.out.println(ss.isEmpty());
//集合的长度,集合元素个数
System.out.println(ss.size());
1.3Collection 集合的遍历
Iterator:迭代器,集合专用遍历方式
Collection<String> ss = new ArrayList<String>();
ss.add("hello");
ss.add("java");
ss.add("牛逼");
// 返回此集合中元素的迭代器,通过集合的iterator()方法得到
Iterator<String> it = ss.iterator();
// Itr是Iterator的实现类
// 返回迭代中的下一个元素
// System.out.println(it.next());
// System.out.println(it.next());
// System.out.println(it.next());
// 如果迭代具有更多元素,则返回true
// if (it.hasNext()) {
// System.out.println(it.next());
// }
// if (it.hasNext()) {
// System.out.println(it.next());
// }
// if (it.hasNext()) {
// System.out.println(it.next());
// }
// 用while循环改进判断
while ( it.hasNext()) {
// System.out.println(it.next());
String s1 = it.next();
System.out.println(s1);
}