Day 07 集合框架入门及泛型介绍
集合框架
Java Platform Enterprise Edition
- 集合的概念
- Collection接口(父接口)
- List接口与实现类
- 泛型和工具类(类型变成参数化使用)
- Set接口与实现类
- Map接口与实现类
什么是集合
- 概念:对象的容器,定义了多个对象进行操作的常用方法。可实现数组的功能
- 和数组的区别:
数组长度固定,集合长度不固定
数组可以存储基本类型和引用类型,集合只能存储引用类型(装箱操作)
- 位置:java.util.*;
Collect体系结合
Java Platform Standard Edition
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xOZu80AV-1632324247817)(C:\Users\50092\Desktop\JAVA\截图\000000001.jpeg)]
Collection :该体系结构的根接口,代表一组对象,称为“集合”
List接口的特点:有序,有下标,元素可重复
set接口的特点:无序,无下标,元素不可重复
Collection父接口及迭代器
特点:代表一组任意类型的对象,无序,无下标,不能重复
方法:
- boolean add(Object obj)//添加一个对象
- boolean addAll(Collection c)//将一个集合中的所有对象添加到此集合中
- void clear()//清空此集合中的所有对象
- boolean contains(Objuct o)//检查此集合中是否包含o对象
- boolean equals(Object o)//比较此集合是都与指定对象相等
- boolean isEmpty()//判断集合是否为空
- boolean remove(Object o)//在此集合中移除o对象
- int size()//返回此集合中的元素个数,用这个的时候前面加集合的名字
- object[ ] toArray()//将此集合转换成数组
boolean add(E e) | 添加指定元素到集合中 |
---|---|
boolean addAll(Collection<? extends E c) | 将相同引用类型的集合中所有元素添加到当前集合 |
void clear() | 移除集合中所有元素 |
boolean contains(Object o) | 返回集合是否包含指定的对象 |
boolean containsAll(Collection<?> c) | 返回当前集合是否包含指定集合的所有元素 |
boolean equals(Object o) | 与指定对象进行比较 |
int hashCode() | 返回当前集合的哈希值 |
boolean isEmpty() | 返回集合是否不包含任意元素 |
Iterator iterator() | 返回集合中的元素的迭代器 |
default Stream parallelStream() | 返回一个当前集合作为数据来源的可能并行的Stream |
boolean remove(Object o) | 从集合中移除指定的元素 |
boolean remove(Collection<?> c) | 移除当前集合中包含的指定集合的所有元素 |
default boolean removeIf(Predicate<? super E> filter) | 移除当前集合中满足指定Predicate的所有元素 |
boolean retainAll(Collection<?> c) | 仅保留当前集合包含的指定集合的所有元素 |
int size() | 返回集合中元素个数 |
default Spliterator spliterator() | 创建当前集合中元素的Spliterator |
default Stream stream() | 返回一个当前集合作为数据来源的Stream |
Object[] toArray() | 返回包含当前集合所有元素的数组;数组类型为Object类型 |
T[] toArray(T[] a) | 返回包含此集合中所有元素的数组;数组类型与元素类型相同 |
package collcetion;
/*
* Collection接口的使用
*1.添加元素
*2.删除元素
*3.遍历元素
*4.判断
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class demo1 {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();//实例化
//1.添加元素
collection.add("牛逼");
collection.add("牛逼2");
System.out.println("元素个数为"+collection.size());
System.out.println(collection);
System.out.println("===============================");
/*2.删除元素
collection.remove("牛逼");
System.out.println(collection);
*/
//3.遍历元素(*重点)
//3.1使用增强for(for each)
for (Object object: collection){
System.out.println(object);
}
System.out.println("==================================");
//3.2使用迭代器(迭代器专门用来遍历集合的一种方式)
/*
Iterator迭代器
hasNext()有没有下一个元素
next();获取下一个元素
remove();删除当前元素
*/
Iterator sb1= collection.iterator();//创建迭代器
while (sb1.hasNext()){
String sb2 = (String) sb1.next();
System.out.println(sb2);
sb1.remove();
}
System.out.println("元素个数为"+collection.size());
/*
Iterator dsds=collection.iterator()
while(dsds.hasNext()){
int dssds = (int) dsds.next();
System.out.println(dssds);
} 练习使用迭代器遍历
*/
//使用迭代器不能使用collection方法
//ConcurrentModificationException 并发修改异常
System.out.println("=====================================");
//4.判断
System.out.println(collection.contains("牛逼"));//true
System.out.println(collection.contains("我草你妈"));//false
System.out.println(collection.isEmpty());
}
}//使用迭代器遍历数组
package collcetion;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class demo02 {
public static void main(String[] args) {
Collection sdds= new ArrayList();//创造集合名字叫sdds
sdds.add("牛逼");//给集合sdds添加元素
sdds.add("傻逼");
Iterator SBB = sdds.iterator();//创造迭代器名字叫SBB
while (SBB.hasNext()){
String sbb =(String) SBB.next();
System.out.println(sbb);//写在大括号外面不识别变量sbb
}
System.out.println(sdds.size());
}
}//练习使用构造器
package collcetion;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class demo03 {
public static void main(String[] args) {
Collection collection1 = new ArrayList();
student s1 = new student("张三",20);
student s2 = new student("张三2",21);
collection1.add(s1);
collection1.add(s2);
System.out.println(collection1.size());
System.out.println(collection1.toString());
System.out.println(collection1);
//增强for
for (Object object:collection1) {
student st2 = (student) object;
System.out.println(st2.toString());
Iterator nb2 = collection1.iterator();
while (nb2.hasNext()){
student st = (student) nb2.next();
System.out.println(st.toString());
}
//判断
System.out.println(collection1.contains(s1));
}
}
}
//创建学生类
package collcetion;
public class student {
private String name;
private int age;
//这一步很重要,如果没定义这一段,前面无法定义元素
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 String toString() {
return "name:" + name + ",age:" + age;
}
}
List子接口
特点:
有序、有下标所以元素可重复。
独有方法:
List 继承自Collection,所以 List 内的方法包含了Collection接口方法,就不再赘述,见上文
void add(int index,E element) | 在List指定位置插入指定的元素 |
---|---|
void addAll(Collection<? extends E> c) | 在List指定位置插入指定集合的所有元素 |
E get(int index) | 返回指定位置的元素 |
int indexOf(Object o) | 返回在List中指定对象第一次出现的索引 |
int lastIndexOf(Object o) | 返回在List中指定对象最后一次出现的索引 |
ListIterator listIterator() | 返回List的ListIterator |
ListIterator listIterator(int index) | 返回List从指定索引开始的ListIterator,ListIterator包含指定索引的元素 |
E remove(int index) | 移除List指定位置的元素 |
boolean replaceAll(UnaryOperator operator) | 使用UnaryOperator替换List中每个元素 |
E set(int index,E element) | 替换List中指定位置的元素 |
default void sort(Comparator<? super E> c) | 使用指定的Comparator对List所有元素进行排序 |
List subList(int fromIndex,int toIndex) | 以List返回指定起始索引到终止索引见的所有元素,包含起始索引对应的元素,不包含终止索引对应的元素 |
Object 元素
6.List 常用实现类
ArrayList | 数组结构实现,查询快、增删慢;JDK1.2 版本支持,运行效率快、线程不安全 |
---|---|
Vector | 数组结构实现,查询快、增删慢;JDK1.0 版本支持,运行效率慢、线程安全 |
LinkedList | 链表结构实现,查询慢、增删快;JDK1.2 版本支持,运行效率快、线程不安全 |
ArrayList
package collcetion;
/*
存储结构:数组,查找遍历速度快,增删慢
* */
import com.sun.xml.internal.ws.api.model.wsdl.WSDLOutput;
import javax.xml.bind.SchemaOutputResolver;
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
public class demo04 {
public static void main(String[] args) {
ArrayList NB = new ArrayList();//创建集合
//添加元素
student s1=new student( "牛皮",21);
student s2=new student("牛皮2",20);
NB.add(s1);
NB.add(s2);
System.out.println(NB.size());
System.out.println(NB.toString());
System.out.println("=============================");
//遍历元素
for (Object object:NB) {
student st2 = (student) object;
System.out.println(st2.toString());
}
System.out.println("======================");
//迭代器遍历元素
Iterator gz=NB.iterator();
while (gz.hasNext()) {
student st3 = (student) gz.next();
System.out.println(st3.toString());
}
System.out.println("===================================================");
//使用列表迭代器
ListIterator LYY = NB.listIterator();//起名字很重要
while (LYY.hasNext()){
student st4 = (student) LYY.next();
System.out.println(st4.toString());
}
System.out.println("===================================================");
//使用列表迭代器逆序
while (LYY.hasPrevious()){
student st4 = (student) LYY.previous();
System.out.println(st4.toString());
}
System.out.println("===================================================");
//判断
System.out.println(NB.contains(s2));
System.out.println(NB.isEmpty());
//查找
System.out.println(NB.indexOf(s1));
}
//列表迭代器必须先定义才能使用逆序?
}
源码分析:DEFAULT_CAPACITY=10; 默认容量大小为10
注意:如果没有向集合中添加任何元素时,容量0,添加任意一个元素后,容量是10,每次扩容大小是原来的1.5倍3
存放元素的数组 elementData
实际的元素个数 size
实际元素个数小于容量
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!! size刚开始为0
elementData[size++] = e;
return true;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
//elementData存放实际数据
//calculateCapacity计算容量
private void ensureExplicitCapacity(int minCapacity//值为10,上面方法传下来) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;//0
int newCapacity = oldCapacity + (oldCapacity >> 1);//0=0+0
if (newCapacity - minCapacity < 0)//0-10《10
newCapacity = minCapacity;//10=10
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);//基本上不成立
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);//newCapacity copy10 给 elementData 所以默认是10
}
LinkedList
package collcetion;
/*
* LinkedList的使用
*存储结构:双向链表
*
* */
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class np2 {
public static void main(String[] args) {
//创建集合
LinkedList LYY = new LinkedList();
//添加元素
student s1=new student( "牛皮",21);
student s2=new student("牛皮2",20);
LYY.add(s1);
LYY.add(s2);
System.out.println(LYY.size());
System.out.println(LYY.toString());
System.out.println("===================");
//遍历 for循环
for (int i=0;i<LYY.size();i++){
System.out.println(LYY.get(i));
}
//遍历 增强for
for (Object object:LYY) {
student LYY2 = (student) object;
System.out.println(LYY2.toString());
}
System.out.println("=============================");
//遍历 迭代器
Iterator LYY3 = LYY.iterator();
while (LYY3.hasNext()){
student lyy2 = (student) LYY3.next();
System.out.println(lyy2.toString());
}
System.out.println("==================");
//遍历 列表迭代器
ListIterator LTT1= LYY.listIterator();
while (LTT1.hasNext()){
student ltt = (student) LTT1.next();
System.out.println(ltt.toString());
}
}
}
vector
package np;
//Vector集合的使用
//储存结构:数组
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
public class demo1 {
public static void main(String[] args) {
Vector LYY = new Vector();//实例化
LYY.add("菊花");
LYY.add("玫瑰");
System.out.println("元素个数"+LYY.size());
System.out.println("===========================");
//遍历(枚举器)
Enumeration lyy=LYY.elements();
while (lyy.hasMoreElements()){
String LYY2=(String) lyy.nextElement();
System.out.println(LYY2);
}
System.out.println("++++++++++++++++++++++++++++");
System.out.println(LYY.firstElement());
System.out.println(LYY.lastElement());
System.out.println(LYY.get(1));
}
}
泛型
- Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递
- 常见形式有泛型类,泛型接口,泛型方法
- 语法:<T,…>T称为类型占位符,表示一种引用类型
- 好处:提高代码的重用性 防止类型转换异常,提高代码的安全性
numeration lyy=LYY.elements();
while (lyy.hasMoreElements()){
String LYY2=(String) lyy.nextElement();
System.out.println(LYY2);
}
System.out.println("++++++++++++++++++++++++++++");
System.out.println(LYY.firstElement());
System.out.println(LYY.lastElement());
System.out.println(LYY.get(1));
}
}
---
## 泛型
- Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递
- 常见形式有泛型类,泛型接口,泛型方法
- 语法:<T,...>T称为类型占位符,表示一种引用类型
- 好处:提高代码的重用性 防止类型转换异常,提高代码的安全性