Collection集合体系
Collection集合是一种单列集合,包含List和Set两类。List常见的有ArrayList和LinkedList,Set常见的有HashSet和TreeSet。
Collection集合常用的方法有:
添加元素:public void add()
移除指定元素:public void remove()
判断集合是否为空:public void isEmpty()
输出元素的个数:public void size()
清空元素:public void clear()
public class CollectionDemo {
public static void main(String[] args) {
Collection<String> c = new ArrayList<String>();
//添加元素
c.add("hello");
c.add("world");
c.add("java");
System.out.println(c);
//删除指定元素
System.out.println(c.remove("world"));
//判断集合是否为空
System.out.println(c.isEmpty());
//得到集合元素个数
System.out.println(c.size());
//清除元素
c.clear();
System.out.println(c);
}
}
[hello, world, java]
true
false
2
[]
利用对象迭代器遍历集合元素,首先要创建集合对象并添加元素,然后用iterator方法调出对象迭代器进行遍历。
public static void main(String[] args) {
Collection<String> c = new ArrayList<String>();//创建集合对象
//添加对象元素
c.add("hello");
c.add("world");
c.add("java");
//调出对象迭代器
Iterator<String> it = c.iterator();
/*逐个输出对象元素
System.out.println(it.next());
System.out.println(it.next());
System.out.println(it.next());
System.out.println(it.next());//NoSuchElementException:对象元素不存在
*/
/*利用if语句判断下个元素是否存在
if (it.hasNext()){
System.out.println(it.next());
}
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());
}
}
hello
world
java