集 合
集合类概述
为什么出现集合类?
面向对象语言对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,Java就提供了集合类。
数组和集合类同是容器,有何不同?
数组虽然也可以存储对象,但长度是固定的;集合长度是可变的。数组中可以存储基本数据类型也可以存储对象,集合只能存储对象。
集合类的特点
集合只用于存储对象,集合长度是可变的,集合可以存储不同类型的对象
Java 集合可分为 Collection 和 Map 两种体系
Collection接口:
Set:元素无序、不可重复的集合
List:元素有序,可重复的集合
Map接口:
具有映射关系“key-value对”的集合
Collection 接口
Collection 接口是 List、Set 和 Queue 接口的父接口,该接口里定义的方法既可用于操作 Set 集合,也可用于操作 List 和 Queue 集合
JDK不提供此接口的任何直接实现,而是提供更具体的子接口(如:Set和List)实现。
在 Java5 之前,Java 集合会丢失容器中所有对象的数据类型,把所有对象都当成 Object 类型处理;从 Java5 增加了泛型以后,Java 集合可以记住容器中对象的数据类型
@Test
public void testCollection1() {
Collection coll = new ArrayList();
// 1.size():返回集合中元素的个数
System.out.println(coll.size());
// 2.add(Object obj):向集合中添加一个元素
coll.add(123);
coll.add("AA");
coll.add(new Date());
coll.add("BB");
System.out.println(coll.size());
// 3.addAll(Collection coll):将形参coll中包含的所有元素添加到当前集合中
Collection coll1 =Arrays.asList(1, 2, 3);
coll.addAll(coll1);
System.out.println(coll.size());
// 查看集合元素
System.out.println(coll);
// 4.isEmpty():判断集合是否为空
System.out.println(coll.isEmpty());
// 5.clear():清空集合元素
coll.clear();
System.out.println(coll.isEmpty());
}
@Test
public void testCollection2() {
Collection coll = new ArrayList();
coll.add(123);
coll.add(new String("AA"));
coll.add(new Date());
coll.add("BB");
// Person p = new Person("MM",23);
coll.add(new Person("MM", 23));
System.out.println(coll);
// 6.contains(Object obj):判断集合中是否包含指定的obj元素。如果包含,返回true,反之返回false
// 判断的依据:根据元素所在的类的equals()方法进行判断
// 明确:如果存入集合中的元素是自定义类的对象。要求:自定义类要重写equals()方法!
boolean b1 = coll.contains(123);
b1 = coll.contains(new String("AA"));
System.out.println(b1);
boolean b2 = coll.contains(new Person("MM", 23));
System.out.println(b2);
// 7.containsAll(Collection coll):判断当前集合中是否包含coll中所有的元素
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add(new String("AA"));
boolean b3 = coll.containsAll(coll1);
System.out.println("#" + b3);
coll1.add(456);
// 8.retainAll(Collection coll):求当前集合与coll的共有的元素,返回给当前集合
coll.retainAll(coll1);
System.out.println(coll);
// 9.remove(Object obj):删除集合中的obj元素。若删除成功,返回true。否则,返回false
boolean b4 = coll.remove("BB");
System.out.println(b4);
}
@Test
public void testCollection3() {
Collection coll = new ArrayList();
coll.add(123);
coll.add(new String("AA"));
coll.add(new Date());
coll.add("BB");
coll.add(new Person("MM", 23));
Collection coll1 = new ArrayList();
coll1.add(123);
coll1.add(new String("AA"));
// 10.removeAll(Collection coll):从当前集合中删除包含在coll中的元素。
coll.removeAll(coll1);
System.out.println(coll);
//11.equals(Object obj):判断集合中的所有元素是否完全相同
Collection coll2 = new ArrayList();
coll2.add(123);
coll2.add(new String("AA1"));
System.out.println(coll1.equals(coll2));
//12.hashCode():
System.out.println(coll.hashCode());
System.out.println();
//13.toArray() :将集合转化为数组
Object[] obj =coll.toArray();
for(int i = 0;i < obj.length;i++){
System.out.println(obj[i]);
}
System.out.println();
//14.iterator():返回一个Iterator接口实现类的对象,进而实现集合的遍历!
Iterator iterator =coll.iterator();
//方式一:不用
/*System.out.println(iterator.next());
System.out.println(iterator.next());
System.out.println(iterator.next());*/
//方式二:不用
// for(int i = 0;i <coll.size();i++){
// System.out.println(iterator.next());
// }
//方式三:使用
while(iterator.hasNext()){
System.out.println(iterator.next());
}
}
使用迭代器Iterator实现集合的遍历
//正确的写法:使用迭代器Iterator实现集合的遍历
@Test
public void test1(){
Collection coll = new ArrayList();
coll.add(123);
coll.add(new String("AA"));
coll.add(new Date());
coll.add("BB");
coll.add(new Person("MM", 23));
Iterator i =coll.iterator();
while(i.hasNext()){
System.out.println(i.next());
}
}
//错误的写法
@Test
public void test2(){
Collection coll = new ArrayList();
coll.add(123);
coll.add(new String("AA"));
coll.add(new Date());
coll.add("BB");
coll.add(new Person("MM", 23));
Iterator i =coll.iterator();
while((i.next())!= null){
//java.util.NoSuchElementException
System.out.println(i.next());
}
}
//使用增强for循环实现集合的遍历
@Test
public void testFor(){
Collection coll = new ArrayList();
coll.add(123);
coll.add(new String("AA"));
coll.add(new Date());
coll.add("BB");
coll.add(new Person("MM", 23));
for(Object i:coll){
System.out.println(i);
}
}
//***********************************************
//使用增强for循环实现数组的遍历
@Test
public void testFor1(){
String[] str = new String[]{"AA","BB","DD"};
for(String s:str){
System.out.println(s);
}
}
@Test
public void testFor2(){
String[] str = new String[]{"AA","BB","DD"};
for(int i = 0;i < str.length;i++){
str[i] = i + "";
}
for(int i = 0;i < str.length;i++){
System.out.println(str[i]);
}
}
//面试题:
@Test
public void testFor3(){
String[] str = new String[]{"AA","BB","DD"};
for(String s : str){
s = "MM";//此处的s是新定义的局部变量,其值的修改不会对str本身造成影响。
System.out.println(s);
}
for(int i = 0;i < str.length;i++){
System.out.println(str[i]);
}
}
List接口
Java中数组用来存储数据的局限性
List集合类中元素有序、且可重复,集合中的每个元素都有其对应的顺序索引。
List容器中的元素都对应一个整数型的序号记载其在容器中的位置,可以根据序号存取容器中的元素。
JDK API中List接口的实现类常用的有:ArrayList、LinkedList和Vector。
List 集合里添加了一些根据索引来操作集合元素的方法
List实现类之一:ArrayList
ArrayList 是 List 接口的典型实现类
本质上,ArrayList是对象引用的一个变长数组
ArrayList 是线程不安全的,而 Vector 是线程安全的,即使为保证List 集合线程安全,也不推荐使用Vector
Arrays.asList(…) 方法返回的 List 集合既不是 ArrayList实例,也不是 Vector 实例。 Arrays.asList(…) 返回值是一个固定长度的List 集合
List实现类之二:LinkedList
对于频繁的插入或删除元素的操作,建议使用LinkedList类,效率较高
List 实现类之三:Vector
Vector 是一个古老的集合,JDK1.0就有了。大多数操作与ArrayList相同,区别之处在于Vector是线程安全的。
在各种list中,最好把ArrayList作为缺省选择。当插入、删除频繁时,使用LinkedList;Vector总是比ArrayList慢,所以尽量避免使用。
public class TestList {
//ArrayList:List的主要实现类
/*
* List中相对于Collection,新增加的方法
* voidadd(int index, Object ele):在指定的索引位置index添加元素ele
boolean addAll(intindex, Collection eles)
Object get(int index):获取指定索引的元素
Object remove(intindex):删除指定索引位置的元素
Object set(int index,Object ele):设置指定索引位置的元素为ele
int indexOf(Objectobj):返回obj在集合中首次出现的位置。没有的话,返回-1
int lastIndexOf(Objectobj):返回obj在集合中最后一次出现的位置.没有的话,返回-1
List subList(intfromIndex, int toIndex):返回从fromIndex到toIndex结束的左闭右开一个子list
List常用的方法:增(add(Object obj)) 删(remove) 改(set(int index,Object obj))
查(get(int index)) 插(add(int index, Object ele)) 长度(size())
*/
@Test
public void testList2(){
List list = new ArrayList();
list.add(123);
list.add(456);
list.add(new String("AA"));
list.add(new String("GG"));
list.add(456);
System.out.println(list.indexOf(456));
System.out.println(list.lastIndexOf(456));
System.out.println(list.indexOf(123)== list.lastIndexOf(123));
System.out.println(list.indexOf(444));
List list1 =list.subList(0, 3);
System.out.println(list1);
}
@Test
public void testList1(){
List list = new ArrayList();
list.add(123);
list.add(456);
list.add(new String("AA"));
list.add(new String("GG"));
System.out.println(list);
list.add(0,555);
System.out.println(list);
Object obj =list.get(1);
System.out.println(obj);
list.remove(0);
System.out.println(list.get(0));
list.set(0, 111);
System.out.println(list.get(0));
}
}
List案例
List集合存储字符串并遍历。
importjava.util.Iterator;
import java.util.List;
importjava.util.ArrayList;
/*
* 需求:List集合存储字符串并遍历。
*/
public class ListDemo {
public static void main(String[]args) {
// 创建集合对象
List list = new ArrayList();
// 创建字符串并添加字符串
list.add("hello");
list.add("world");
list.add("java");
// 遍历集合
Iterator it =list.iterator();
while (it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
}
}
}
List集合的特有功能
import java.util.ArrayList;
import java.util.List;
/*
* List集合的特有功能:
* A:添加功能
* void add(int index,Object element):在指定位置添加元素
* B:获取功能
* Object get(int index):获取指定位置的元素
* D:删除功能
* Object remove(int index):根据索引删除元素,返回被删除的元素
* E:修改功能
* Object set(int index,Object element):根据索引修改元素,返回被修饰的元素
*/
public class ListDemo {
public static void main(String[]args) {
// 创建集合对象
List list = new ArrayList();
// 添加元素
list.add("hello");
list.add("world");
list.add("java");
// void add(int index,Object element):在指定位置添加元素
// list.add(1, "android");//没有问题
// IndexOutOfBoundsException
// list.add(11, "javaee");//有问题
// list.add(3, "javaee"); //没有问题
// list.add(4, "javaee"); //有问题
// Object get(int index):获取指定位置的元素
// System.out.println("get:" + list.get(1));
// IndexOutOfBoundsException
// System.out.println("get:" + list.get(11));
// Object remove(int index):根据索引删除元素,返回被删除的元素
// System.out.println("remove:" + list.remove(1));
// IndexOutOfBoundsException
// System.out.println("remove:" + list.remove(11));
// Object set(int index,Object element):根据索引修改元素,返回被修饰的元素
System.out.println("set:" + list.set(1, "javaee"));
System.out.println("list:" + list);
}
}
List遍历功能
importjava.util.ArrayList;
import java.util.List;
/*
* List集合的特有遍历功能:
* size()和get()方法结合使用
*/
public class ListDemo2 {
public static void main(String[]args) {
// 创建集合对象
List list = new ArrayList();
// 添加元素
list.add("hello");
list.add("world");
list.add("java");
// Object get(int index):获取指定位置的元素
// System.out.println(list.get(0));
// System.out.println(list.get(1));
// System.out.println(list.get(2));
// IndexOutOfBoundsException
// System.out.println(list.get(3));
// 用循环改进
// for (int x = 0; x < 3; x++) {
// System.out.println(list.get(x));
// }
// 如果元素过多,数起来就比较麻烦,所以我们使用集合的一个长度功能:size()
// 最终的遍历方式就是:size()和get()
for (int x = 0; x < list.size(); x++) {
// System.out.println(list.get(x));
String s = (String)list.get(x);
System.out.println(s);
}
}
}
List:(面试题List的子类特点)
ArrayList:
底层数据结构是数组,查询快,增删慢。
线程不安全,效率高。
Vector:
底层数据结构是数组,查询快,增删慢。
线程安全,效率低。
LinkedList:
底层数据结构是链表,查询慢,增删快。
线程不安全,效率高。
List有三个儿子,我们到底使用谁呢?
看需求(情况)。
要安全吗?
要:Vector(即使要安全,也不用这个了,后面有替代的)
不要:ArrayList或者LinkedList
查询多:ArrayList
增删多:LinkedList
如果你什么都不懂,就用ArrayList。
ArrayList类概述
底层数据结构是数组,查询快,增删慢
线程不安全,效率高
ArrayList案例
importjava.util.ArrayList;
importjava.util.Iterator;
/*
* List的子类特点:
* ArrayList:
* 底层数据结构是数组,查询快,增删慢
* 线程不安全,效率高
* Vector:
* 底层数据结构是数组,查询快,增删慢
* 线程安全,效率低
* LinkedList:
* 底层数据结构是链表,查询慢,增删快
* 线程不安全,效率高
*
* 案例:
* 使用List的任何子类存储字符串或者存储自定义对象并遍历。
*
* ArrayList的使用。
* 存储字符串并遍历
*/
public class ArrayListDemo {
public static void main(String[]args) {
// 创建集合对象
ArrayList array = new ArrayList();
// 创建元素对象,并添加元素
array.add("hello");
array.add("world");
array.add("java");
// 遍历
Iterator it =array.iterator();
while (it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
}
System.out.println("-----------");
for (int x = 0; x < array.size(); x++) {
String s = (String)array.get(x);
System.out.println(s);
}
}
}
集合对象
importjava.util.ArrayList;
importjava.util.Iterator;
/*
* ArrayList存储自定义对象并遍历
*/
public class ArrayListDemo2 {
public static void main(String[]args) {
// 创建集合对象
ArrayList array = new ArrayList();
// 创建学生对象
Student s1 = new Student("武松", 30);
Student s2 = new Student("鲁智深", 40);
Student s3 = new Student("林冲", 36);
Student s4 = new Student("杨志", 38);
// 添加元素
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
// 遍历
Iterator it =array.iterator();
while (it.hasNext()) {
Student s = (Student)it.next();
System.out.println(s.getName()+ "---" + s.getAge());
}
System.out.println("----------------");
for (int x = 0; x < array.size(); x++) {
// ClassCastException 注意,千万要搞清楚类型
// String s = (String) array.get(x);
// System.out.println(s);
Student s = (Student)array.get(x);
System.out.println(s.getName()+ "---" + s.getAge());
}
}
}
Vector类概述及使用
Vector类概述
底层数据结构是数组,查询快,增删慢
线程安全,效率低
Vector类特有功能
public void addElement(E obj)
public E elementAt(int index)
public Enumeration elements()
Vector案例
存储字符串并遍历
存储自定义对象并遍历
importjava.util.Enumeration;
importjava.util.Vector;
/*
* Vector的特有功能:
* 1:添加功能
* public void addElement(Object obj) -- add()
* 2:获取功能
* public Object elementAt(int index) -- get()
* public Enumeration elements() -- Iterator iterator()
* boolean hasMoreElements() hasNext()
* Object nextElement() next()
*
* JDK升级的原因:
* A:安全
* B:效率
* C:简化书写
*/
public class VectorDemo {
public static void main(String[]args) {
// 创建集合对象
Vector v = new Vector();
// 添加功能
v.addElement("hello");
v.addElement("world");
v.addElement("java");
// 遍历
for (int x = 0; x < v.size(); x++) {
String s = (String) v.elementAt(x);
System.out.println(s);
}
System.out.println("------------------");
Enumeration en =v.elements(); // 返回的是实现类的对象
while (en.hasMoreElements()) {
String s = (String)en.nextElement();
System.out.println(s);
}
}
}
LinkedList类概述及使用
LinkedList类概述
底层数据结构是链表,查询慢,增删快
线程不安全,效率高
LinkedList类特有功能
public void addFirst(E e)及addLast(E e)
public E getFirst()及getLast()
public E removeFirst()及public E removeLast()
LinkedList案例
存储字符串并遍历
存储自定义对象并遍历
importjava.util.LinkedList;
/*
* LinkedList的特有功能:
* A:添加功能
* public void addFirst(Object e)
* public void addLast(Object e)
* B:获取功能
* public Object getFirst()
* public Obejct getLast()
* C:删除功能
* public Object removeFirst()
* public ObjectremoveLast()
*/
public class LinkedListDemo {
public static void main(String[]args) {
// 创建集合对象
LinkedList link = new LinkedList();
// 添加元素
link.add("hello");
link.add("world");
link.add("java");
// public void addFirst(Object e)
// link.addFirst("javaee");
// public void addLast(Object e)
// link.addLast("android");
// public Object getFirst()
// System.out.println("getFirst:" + link.getFirst());
// public Obejct getLast()
// System.out.println("getLast:" + link.getLast());
// public Object removeFirst()
System.out.println("removeFirst:" + link.removeFirst());
// public Object removeLast()
System.out.println("removeLast:" +link.removeLast());
// 输出对象名
System.out.println("link:" + link);
}
}
去除集合中字符串的重复值(字符串的内容相同)
importjava.util.ArrayList;
importjava.util.Iterator;
/*
* ArrayList去除集合中字符串的重复值(字符串的内容相同)
*
* 分析:
* A:创建集合对象
* B:添加多个字符串元素(包含内容相同的)
* C:创建新集合
* D:遍历旧集合,获取得到每一个元素
* E:拿这个元素到新集合去找,看有没有
* 有:不搭理它
* 没有:就添加到新集合
* F:遍历新集合
*/
public class ArrayListDemo {
public static void main(String[]args) {
// 创建集合对象
ArrayList array = new ArrayList();
// 添加多个字符串元素(包含内容相同的)
array.add("hello");
array.add("world");
array.add("java");
array.add("world");
array.add("java");
array.add("world");
array.add("world");
array.add("world");
array.add("world");
array.add("java");
array.add("world");
// 创建新集合
ArrayList newArray = new ArrayList();
// 遍历旧集合,获取得到每一个元素
Iterator it = array.iterator();
while (it.hasNext()) {
String s = (String)it.next();
// 拿这个元素到新集合去找,看有没有
if (!newArray.contains(s)) {
newArray.add(s);
}
}
// 遍历新集合
for (int x = 0; x < newArray.size();x++) {
String s = (String)newArray.get(x);
System.out.println(s);
}
}
}
方案二
importjava.util.ArrayList;
importjava.util.Iterator;
/*
* 需求:ArrayList去除集合中字符串的重复值(字符串的内容相同)
* 要求:不能创建新的集合,就在以前的集合上做。
*/
public class ArrayListDemo2 {
public static void main(String[]args) {
// 创建集合对象
ArrayList array = new ArrayList();
// 添加多个字符串元素(包含内容相同的)
array.add("hello");
array.add("world");
array.add("java");
array.add("world");
array.add("java");
array.add("world");
array.add("world");
array.add("world");
array.add("world");
array.add("java");
array.add("world");
// 由选择排序思想引入,我们就可以通过这种思想做这个题目
// 拿0索引的依次和后面的比较,有就把后的干掉
// 同理,拿1索引...
for (int x = 0; x < array.size() - 1;x++) {
for (int y = x + 1; y < array.size();y++) {
if (array.get(x).equals(array.get(y))) {
array.remove(y);
y--;
}
}
}
// 遍历集合
Iterator it =array.iterator();
while (it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
}
}
}
去除集合中自定义对象的重复值(对象的成员变量值都相同)
importjava.util.ArrayList;
importjava.util.Iterator;
/*
* 需求:去除集合中自定义对象的重复值(对象的成员变量值都相同)
*
* 我们按照和字符串一样的操作,发现出问题了。
* 为什么呢?
* 我们必须思考哪里会出问题?
* 通过简单的分析,我们知道问题出现在了判断上。
* 而这个判断功能是集合自己提供的,所以我们如果想很清楚的知道它是如何判断的,就应该去看源码。
* contains()方法的底层依赖的是equals()方法。
* 而我们的学生类中没有equals()方法,这个时候,默认使用的是它父亲Object的equals()方法
* Object()的equals()默认比较的是地址值,所以,它们进去了。因为new的东西,地址值都不同。
* 按照我们自己的需求,比较成员变量的值,重写equals()即可。
* 自动生成即可。
*/
public class ArrayListDemo3 {
public static void main(String[]args) {
// 创建集合对象
ArrayList array = new ArrayList();
// 创建学生对象
Student s1 = new Student("林青霞", 27);
Student s2 = new Student("林志玲", 40);
Student s3 = new Student("凤姐", 35);
Student s4 = new Student("芙蓉姐姐", 18);
Student s5 = new Student("翠花", 16);
Student s6 = new Student("林青霞", 27);
Student s7 = new Student("林青霞", 18);
// 添加元素
array.add(s1);
array.add(s2);
array.add(s3);
array.add(s4);
array.add(s5);
array.add(s6);
array.add(s7);
// 创建新集合
ArrayList newArray = new ArrayList();
// 遍历旧集合,获取得到每一个元素
Iterator it =array.iterator();
while (it.hasNext()) {
Student s = (Student)it.next();
// 拿这个元素到新集合去找,看有没有
if (!newArray.contains(s)) {
newArray.add(s);
}
}
// 遍历新集合
for (int x = 0; x < newArray.size();x++) {
Student s = (Student)newArray.get(x);
System.out.println(s.getName()+ "---" + s.getAge());
}
}
}
public class Student {
private String name;
private int age;
public Student() {
super();
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other =(Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}