一、什么是集合
概念:对象的容器,定义了对多个对象进行操作的常用方法。可实现数组的功能。
和数组区别:
(1)数组长度固定,集合长度不固定
(2)数组可以存储基本类型和引用类型,集合只能存储引用类型。位置: java.util.*;
二、Collection体系集合
2.1 Collection父接口
Colleetion层次结构中的根接口。Collection 表示一组对象,这些对象也称为collection的元素。一些collction允许有重复的元素,而另一些则不允许。一些collection是有序的,而另一些则是无序的。JDK不提供此接口的任何直接实现:它提供更具体的子接口(如Set.和List)实现此接口通常用来传递collection,并在需要最大普遍性的地方操作这些collection
方法:
boolean add (Object obj)//添加一个对象。
boolean addAll(Collection c)//将一个集合中的所有对象添加到此集合中.
void clear()//清空此集合中的所有对象。
boolean contains(Object o)//检查此集合中是否包含o对象。 boolean equals(Object o)//比较此集合是否与指定对象相等。- boolean isEmpty()//判断此集合是否为空
boolean remove(Object o)//在此集合中移除o对象.
int size()//返回此集合中的元素个数。
0bject[] toArray()//将此集合转换成数组。
迭代器:Iterator
boolean hasNext() : 如果仍有元素可以迭代,则可以返回true
next() : 返回迭代的下一个元素
void remove() : 从迭代器指向的collection 中移除迭代器返回的最后一个元素(可选操作)
迭代器应用实例
package collection;
public class Student {
private String name;
private int age;
public Student(String name,int age){
super();
this.name=name;
this.age=age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
package collection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo1 {
public static void main(String[] args) {
//建一个collection对象
Collection collection=new ArrayList();
Student s1=new Student("张三",20);
Student s2=new Student("李四",24);
Student s3=new Student("王五",23);
Student s4=new Student("孙六",26);
//添加数据
collection.add(s1);
collection.add(s2);
collection.add(s3);
collection.add(s4);
System.out.println("元素个数:"+collection.size());
// System.out.println(collection.toString());
//删除
// collection.remove(s1);
// System.out.println("删除之后:"+collection.toString());
//遍历
//增强for
System.out.println("-------------");
/* for(Object object: collection){
Student s=(Student)object;
System.out.println(s.toString());
}*/
//遍历collection集合
//迭代器 hasNext()、next()、remove();迭代过程中不能使用collection的删除方法
Iterator it = collection.iterator();
while(it.hasNext()){
Student s=(Student) it.next();
System.out.println(s.toString());
}
}
}
元素个数:4
-------------
Student{
name='张三', age=20}
Student{
name='李四', age=24}
Student{
name='王五', age=23}
Student{
name='孙六', age=26}
Process finished with exit code 0
三、List集合
list接口的特点:
1、有序的集合,存储元素和取出元素的顺序是一致的(存储123 取出123)
2、有索引,包含了一些带索引的方法
3、允许存储重复元素
list接口中带索引的方法:
public void add(int index,E element):将指定元素添加到该集合的指定位置
public E get (int index):返回集合指定位置的元素
public E remove(int index):移除集合中指定位置的元素,返回值是被删除掉的元素
public E set(int index, E element):用指定元素替换集合中指定位置的元素,返回值是更新前的元素
boolean addAll(int index,Collection c) //将一个集合中的元素添加到此集合中的index位置
List subList(int fromIndex,int toIndex) 返回fromIndex和toIndex之间的集合元素
package collection;
import java.util.ArrayList;
import java.util.List;