集合概述
概念:对象的容器,定义了对多个对象进项操作的的常用方法。可实现数组的功能。
和数组的区别:
数组长度固定,集合长度不固定。
数组可以存储基本类型和引用类型,集合只能存储引用类型。
位置: java.util.*;
Collection体系集合
Collection父接口
特点:代表一组任意类型的对象,无序、无下标、不能重复。
方法:
boolean add(Object obj)//添加一个对象。
boolean addAll(Collection c)//将一个集合中所有的对象添加到此集合当中。
void clear()//清空此集合中的所有对象。
boolean contains(Object o) //检查此集合中是否包含o对象。
boolean equals(Object o) // 比较此集合是否与指定对象相等。
boolean isEmpty()//判断此集合是否为空。
boolean remov(Object o)//在此集合中移除o对象。
int size() //返回此集合中的元素个数。
Object[] toArray()//将此集合转换成数组。
/**
*Collection 接口的使用(一)
*1.添加元素
*2.删除元素
*3.遍历元素
*4.判断
*/
public class Demo01{
pubic static void main(String[] args){
//创建集合
Collection collection=new ArrayList();
// * 1.添加元素
Collection.add("苹果");
Collection.add("西瓜");
Collection.add("榴莲");
System.out.println("元素个数:"+collection.size());
System.out.println(collection);
// * 2.删除元素
collection.remove("榴莲");
System.out.println("删除之后:"+collection.size());
// * 3.遍历元素
//3.1 使用增强for
for(Object object : collection){
System.out.println(object);
}
//3.2 使用迭代器(迭代器专门用来遍历集合的一种方式)
//hasnext();判断是否有下一个元素
//next();获取下一个元素
//remove();删除当前元素
Iterator iterator=collection.Itertor();
while(iterator.hasnext()){
String object=(String)iterator.next();
System.out.println(s);
//删除操作
//collection.remove(s);引发错误:并发修改异常
//iterator.remove();应使用迭代器的方法
// * 4.判断
System.out.println(collection.contains("西瓜"));//true
System.out.println(collection.isEmpty());//false
}
}
}
/**
* Collection接口的使用(二)
* 1.添加元素
* 2.删除元素
* 3.遍历元素
* 4.判断
*/
public class Demo2 {
public static void main(String[] args) {
Collection collection=new ArrayList();
Student s1=new Student("张三",18);
Student s2=new Student("李四", 20);
Student s3=new Student("王五", 19);
//1.添加数据
collection.add(s1);
collection.add(s2);
collection.add(s3);
//collection.add(s3);可重复添加相同对象
System.out.println("元素个数:"+collection.size());
System.out.println(collection.toString());
//2.删除数据
collection.remove(s1);
System.out.println("删除之后:"+collection.size());
//3.遍历数据
//3.1 增强for
for(Object object:collection) {
Student student=(Student) object;
System.out.println(student.toString());
}
//3.2迭代器
//迭代过程中不能使用collection的删除方法
Iterator iterator=collection.iterator();
while (iterator.hasNext()) {
Student student=(Student) iterator.next();
System.out.println(student.toString());
}
//4.判断和上一块代码类似。
}
}
/**
* 学生类
*/
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 "Student [name=" + name + ", age=" + age +"]";
}
}
Collection子接口
List集合
特点:有序 、有下标、元素可以重复。
方法:
void add(int index,Object o) //在index位置插入对象o。
boolean addAll(index,Collection c) //将一个集合中的元素添加到此集合中的index位置。
Object get(int index) //返回集合中指定位置的元素。
List subList(int fromIndex,int toIndex) //返回fromIndex和toIndex之间的集合元素。
/**
* List子接口的使用(一)
* 特点:1.有序有下标 2.可以重复
*
* 1.添加元素
* 2.删除元素
* 3.遍历元素
* 4.判断
* 5.获取位置
*/
/**
* List子接口的使用(一)
* 特点:1.有序有下标 2.可以重复
*
* 1.添加元素
* 2.删除元素
* 3.遍历元素
* 4.判断
* 5.获取位置
*/
public class Demo3 {
public static void main(String[] args) {
List list=new ArrayList<>();
//1.添加元素
list.add("tang");
list.add("he");
list.add(0,"yu");//插入操作
System.out.println("元素个数:"+list.size());
System.out.println(list.toString());
//2.删除元素
list.remove(0);
//list.remove("yu");结果同上
System.out.println("删除之后:"+list.size());
System.out.println(list.toString());
//3.遍历元素
//3.1 使用for遍历
for(int i=0;i<list.size();++i) {
System.out.println(list.get(i));
}
//3.2 使用增强for
for(Object object:list) {
System.out.println(object);
}
//3.3 使用迭代器
Iterator iterator=list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
//3.4使用列表迭代器,listIterator可以双向遍历,添加、删除及修改元素。
ListIterator listIterator=list.listIterator();
//从前往后
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}
//从后往前(此时“遍历指针”已经指向末尾)
while(listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
//4.判断
System.out.println(list.isEmpty());
System.out.println(list.contains("tang"));
//5.获取位置
System.out.println(list.indexOf("tang"));
}
}
/**
* List子接口的使用(二)
* 1.添加元素
* 2.删除元素
* 3.遍历元素
* 4.判断
* 5.获取位置
*/
public class Demo4 {
public static void main(String[] args) {
List list=new ArrayList();
//1.添加数字数据(自动装箱)
list.add(20);
list.add(30);
list.add(40);
list.add(50);
System.out.println("元素个数:"+list.size());
System.out.println(list.toString());
//2.删除元素
list.remove(0);
//list.remove(20);很明显数组越界错误,改成如下
//list.remove(Object(20));
//list.remove(new Integer(20));
System.out.println("元素个数:"+list.size());
System.out.println(list.toString());
//3-5不再演示,与之前类似
//6.补充方法subList,返回子集合,含头不含尾
List list2=list.subList(1, 3);
System.out.println(list2.toString());
}
}
List实现类
ArrayList【重点】
数组结构实现,查询快、增删慢;
JDK1.2版本,运行效率快、线程不安全。
/**
* ArrayList的使用
* 存储结构:数组;
* 特点:查找遍历速度快,增删慢。
* 1.添加元素
* 2.删除元素
* 3.遍历元素
* 4.判断
* 5.查找
*/
public class Demo5 {
public static void main(String[] args) {
ArrayList arrayList=new ArrayList<>();
//1.添加元素
Student s1=new Student("唐", 21);
Student s2=new Student("何", 22);
Student s3=new Student("余", 21);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println("元素个数:"+arrayList.size());
System.out.println(arrayList.toString());
//2.删除元素
arrayList.remove(s1);
//arrayList.remove(new Student("唐", 21));
//注:这样可以删除吗(不可以)?显然这是两个不同的对象。
//假如两个对象属性相同便认为其是同一对象,那么如何修改代码?
//3.遍历元素
//3.1使用迭代器
Iterator iterator=arrayList.iterator();
while(iterator.hasNext()) {
System.out.println(iterator.next());
}
//3.2使用列表迭代器
ListIterator listIterator=arrayList.listIterator();
//从前往后遍历
while(listIterator.hasNext()) {
System.out.println(listIterator.next());
}
//从后往前遍历
while(listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
//4.判断
System.out.println(arrayList.isEmpty());
//System.out.println(arrayList.contains(new Student("何", 22)));
//注:与上文相同的问题。
//5.查找
System.out.println(arrayList.indexOf(s1));
}
}
注:Object里的equals(this==obj)用地址和当前对象比较,如果想实现代码中的问题,可以在学生类中重写equals方法:
@Override
public boolean equals(Object obj) {
//1.是否为同一对象
if (this==obj) {
return true;
}
//2.判断是否为空
if (obj==null) {
return false;
}
//3.判断是否是Student类型
if (obj instanceof Student) {
Student student=(Student) obj;
//4.比较属性
if(this.name.equals(student.getName())&&this.age==student.age) {
return true;
}
}
//不满足,返回false
return false;
}
Vector
数组结构实现、查询快、增删慢;
JDK1.0版本,运行效率慢、线程安全。
/**
* Vector的演示使用
*
*1.添加数据
*2.删除数据
*3.遍历
*4.判断
*/
public class Demo1 {
public static void main(String[] args) {
Vector vector=new Vector<>();
//1.添加数据
vector.add("tang");
vector.add("he");
vector.add("yu");
System.out.println("元素个数:"+vector.size());
//2.删除数据
/*
* vector.remove(0); vector.remove("tang");
*/
//3.遍历
//使用枚举器
Enumeration enumeration=vector.elements();
while (enumeration.hasMoreElements()) {
String s = (String) enumeration.nextElement();
System.out.println(s);
}
//4.判断
System.out.println(vector.isEmpty());
System.out.println(vector.contains("he"));
//5. Vector其他方法
//firstElement() lastElement() ElementAt();
}
}
LinkedList
链表 结构实现,增删快,查询慢。
/**
* LinkedList的用法
* 存储结构:双向链表
* 1.添加元素
* 2.删除元素
* 3.遍历
* 4.判断
*/
public class Demo2 {
public static void main(String[] args) {
LinkedList linkedList=new LinkedList<>();
Student s1=new Student("唐", 21);
Student s2=new Student("何", 22);
Student s3=new Student("余", 21);
//1.添加元素
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
linkedList.add(s3);
System.out.println("元素个数:"+linkedList.size());
System.out.println(linkedList.toString());
//2.删除元素
/*
* linkedList.remove(new Student("唐", 21));
* System.out.println(linkedList.toString());
*/
//3.遍历
//3.1 使用for
for(int i=0;i<linkedList.size();++i) {
System.out.println(linkedList.get(i));
}
//3.2 使用增强for
for(Object object:linkedList) {
Student student=(Student) object;
System.out.println(student.toString());
}
//3.3 使用迭代器
Iterator iterator =linkedList.iterator();
while (iterator.hasNext()) {
Student student = (Student) iterator.next();
System.out.println(student.toString());
}
//3.4 使用列表迭代器(略)
//4. 判断
System.out.println(linkedList.contains(s1));
System.out.println(linkedList.isEmpty());
System.out.println(linkedList.indexOf(s3));
}
}
ArrayList和LinkedList区别
ArrayList:必须开辟连续空间,查询快,增删慢。
LinkedList:无需开辟连续空间,查询慢,增删快。
泛型概述
Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。
常见形式有泛型类、泛型接口、泛型方法。
语法:
<T,…> T称为类型占位符,表示一种引用类型。
好处:
提高代码的重用性。
防止类型转换异常,提高代码的安全性。
帮助程序员把代码写正确。
泛型类
/**
*泛型类
*语法:类名
*T是类型占位符,表示一种引用类型,编写多个使用逗号隔开
*/
public class myGeneric<T>{
//1.创建泛型变量
//不能使用new来创建,因为泛型是不确定的类型,也可能拥有私密的构造方法。
T t;
//2.泛型作为方法的参数
public void show(T t) {
System.out.println(t);
}
//泛型作为方法的返回值
public T getT() {
return t;
}
}
/**
* 注意:
* 1.泛型只能使用引用类型
* 2.不同泛型类型的对象不能相互赋值
*/
public class testGeneric {
public static void main(String[] args) {
//使用泛型类创建对象
myGeneric<String> myGeneric1=new myGeneric<String>();
myGeneric1.t="tang";
myGeneric1.show("he");
myGeneric<Integer> myGeneric2=new myGeneric<Integer>();
myGeneric2.t=10;
myGeneric2.show(20);
Integer integer=myGeneric2.getT();
}
}
泛型接口
/**
* 泛型接口
* 语法:接口名<T>
* 注意:不能创建泛型静态常量
*/
public interface MyInterface<T> {
//创建常量
String nameString="tang";
T server(T t);
}
/**
* 实现接口时确定泛型类
*/
public class MyInterfaceImpl implements MyInterface<String>{
@Override
public String server(String t) {
System.out.println(t);
return t;
}
}
//测试
MyInterfaceImpl myInterfaceImpl=new MyInterfaceImpl();
myInterfaceImpl.server("xxx");
//xxx
/**
* 实现接口时不确定泛型类
*/
public class MyInterfaceImpl2<T> implements MyInterface<T>{
@Override
public T server(T t) {
System.out.println(t);
return t;
}
}
//测试
MyInterfaceImpl2<Integer> myInterfaceImpl2=new MyInterfaceImpl2<Integer>();
myInterfaceImpl2.server(2000);
//2000
泛型方法
/**
* 泛型方法
* 语法:<T> 返回类型
*/
public class MyGenericMethod {
public <T> void show(T t) {
System.out.println("泛型方法"+t);
}
}
//测试
MyGenericMethod myGenericMethod=new MyGenericMethod();
myGenericMethod.show("tang");
myGenericMethod.show(200);
myGenericMethod.show(3.14);
泛型集合
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致。
特点:
编译时即可检查,而非运行时抛出异常。
访问时,不必类型转换(拆箱)。
不同泛型之间引用不能相互赋值,泛型不存在多态。
Set集合概述
set子接口
特点:无序、无下标、元素不可重复。
方法:全部继承自Collection中的方法。
/**
* 测试Set接口的使用
* 特点:1.无序,没有下标;2.重复
* 1.添加数据
* 2.删除数据
* 3.遍历【重点】
* 4.判断
*/
public class Demo1 {
public static void main(String[] args) {
Set<String> set=new HashSet<String>();
//1.添加数据
set.add("tang");
set.add("he");
set.add("yu");
System.out.println("数据个数:"+set.size());
System.out.println(set.toString());//无序输出
//2.删除数据
/*
* set.remove("tang"); System.out.println(set.toString());
*/
//3.遍历【重点】
//3.1 使用增强for
for (String string : set) {
System.out.println(string);
}
//3.2 使用迭代器
Iterator<String> iterator=set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
//4.判断
System.out.println(set.contains("tang"));
System.out.println(set.isEmpty());
}
}
Set实现类
HashSet【重点】
基于HashCode计算元素存放位置。
当存入元素的哈希吗相同时,会调用equals进行确认,如结果为true,则拒绝后者存入。
/**
* 人类
*/
public class Person {
private String name;
private int age;
public Person(String name,int age) {
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 "Peerson [name=" + name + ", age=" + age + "]";
}
}
/**
* HashSet集合的使用
* 存储结构:哈希表(数组+链表+红黑树)
* 1.添加元素
* 2.删除元素
* 3.遍历
* 4.判断
*/
public class Demo3 {
public static void main(String[] args) {
HashSet<Person> hashSet=new HashSet<>();
Person p1=new Person("tang",21);
Person p2=new Person("he", 22);
Person p3=new Person("yu", 21);
//1.添加元素
hashSet.add(p1);
hashSet.add(p2);
hashSet.add(p3);
//重复,添加失败
hashSet.add(p3);
//直接new一个相同属性的对象,依然会被添加,不难理解。
//假如相同属性便认为是同一个对象,怎么修改?
hashSet.add(new Person("yu", 21));
System.out.println(hashSet.toString());
//2.删除元素
hashSet.remove(p2);
//3.遍历
//3.1 增强for
for (Person person : hashSet) {
System.out.println(person);
}
//3.2 迭代器
Iterator<Person> iterator=hashSet.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
//4.判断
System.out.println(hashSet.isEmpty());
//直接new一个相同属性的对象结果输出是false,不难理解。
//注:假如相同属性便认为是同一个对象,该怎么做?
System.out.println(hashSet.contains(new Person("tang", 21)));
}
}
注:hashSet存储过程:
1.根据hashCode计算保存的位置,如果位置为空,则直接保存,否则执行第二步。
2.执行equals方法,如果方法返回true,则认为是重复,拒绝存储,否则形成链表。
存储过程实际上就是重复依据,要实现“注”里的问题,可以重写hashCode和equals代码:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) 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;
}
hashCode方法里面为什么要使用31这个数字大概有两个原因:
1.31是一个质数,这样的数字在计算时可以尽量减少散列冲突。
2.可以提高执行效率,因为31*i=(i<<5)-i,31乘以一个数可以转换成移位操作,这样能快一点;但是也有网上一些人对这两点提出质疑。
TreeSet
基于排序顺序实现不重复。
实现了SortedSet接口,对集合元素自动排序。
元素对象的类型必须实现Comparable接口,指定排序规则。
通过Compare To方法确定是否为重复元素。
/**
* 使用TreeSet保存数据
* 存储结构:红黑树
* 要求:元素类必须实现Comparable接口,compareTo方法返回0,认为是重复元素
*/
public class Demo4 {
public static void main(String[] args) {
TreeSet<Person> persons=new TreeSet<Person>();
Person p1=new Person("tang",21);
Person p2=new Person("he", 22);
Person p3=new Person("yu", 21);
//1.添加元素
persons.add(p1);
persons.add(p2);
persons.add(p3);
//注:直接添加会报类型转换错误,需要实现Comparable接口
System.out.println(persons.toString());
//2.删除元素
persons.remove(p1);
persons.remove(new Person("he", 22));
System.out.println(persons.toString());
//3.遍历(略)
//4.判断
System.out.println(persons.contains(new Person("yu", 21)));
}
}
Map体系集合
Map接口的特点:
1.用于存储任意键值对(Key-Value)
2.键:无序,无下标,不允许重复(唯一)。
3.值:无序,无下标,允许重复。
Map集合概述
特点:存储一对数据(Key-Value),无序,无下标,键不可重复。
方法:
V put(k key,V value)//将对象存入到集合中,关联键值。key重复则覆盖原值。
Object get(Object key)//根绝键获取相应的值。
Set<k>//返回所有的key
Collection<V> values() //返回包含所有值的Collection集合。
Set<Map.Entry<k,v>>//键值匹配的set集合
/**
* Map接口的使用
* 特点:1.存储键值对 2.键不能重复,值可以重复 3.无序
*/
public class Demo1 {
public static void main(String[] args) {
Map<String,Integer> map=new HashMap<String, Integer>();
//1.添加元素
map.put("tang", 21);
map.put("he", 22);
map.put("fan", 23);
System.out.println(map.toString());
//2.删除元素
map.remove("he");
System.out.println(map.toString());
//3.遍历
//3.1 使用keySet();
for (String key : map.keySet()) {
System.out.println(key+" "+map.get(key));
}
//3.2 使用entrySet();效率较高
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
Map集合的实现类
HashMap【重点】
JDK1.2版本,线程不安全,运行效率快;允许用null作为key或是value。
/**
* 学生类
*/
public class Student {
private String name;
private int id;
public Student(String name, int id) {
super();
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + id + "]";
}
}
/**
* HashMap的使用
* 存储结构:哈希表(数组+链表+红黑树)
*/
public class Demo2 {
public static void main(String[] args) {
HashMap<Student, String> hashMap=new HashMap<Student, String>();
Student s1=new Student("tang", 36);
Student s2=new Student("yu", 101);
Student s3=new Student("he", 10);
//1.添加元素
hashMap.put(s1, "成都");
hashMap.put(s2, "杭州");
hashMap.put(s3, "郑州");
//添加失败,但会更新值
hashMap.put(s3,"上海");
//添加成功,不过两个属性一模一样;
//注:假如相同属性便认为是同一个对象,怎么修改?
hashMap.put(new Student("he", 10),"上海");
System.out.println(hashMap.toString());
//2.删除元素
hashMap.remove(s3);
System.out.println(hashMap.toString());
//3.遍历
//3.1 使用keySet()遍历
for (Student key : hashMap.keySet()) {
System.out.println(key+" "+hashMap.get(key));
}
//3.2 使用entrySet()遍历
for (Entry<Student, String> entry : hashMap.entrySet()) {
System.out.println(entry.getKey()+" "+entry.getValue());
}
//4.判断
//注:同上
System.out.println(hashMap.containsKey(new Student("he", 10)));
System.out.println(hashMap.containsValue("成都"));
}
}
注:和之前说过的HashSet类似,重复依据是hashCode和equals方法,重写即可:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@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 (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
Collections工具类
概念:集合工具类,定义了除了存取以外的集合常用方法。
方法:
public static void reverse(List<?> list)//反转集合中元素的顺序
public static void shuffle(List<?> list)//随机重置集合元素的顺序
public static void sort(List list)//升序排序(元素类型必须实现Comparable接口)
/**
* 演示Collections工具类的使用
*
*/
public class Demo4 {
public static void main(String[] args) {
List<Integer> list=new ArrayList<Integer>();
list.add(20);
list.add(10);
list.add(30);
list.add(90);
list.add(70);
//sort排序
System.out.println(list.toString());
Collections.sort(list);
System.out.println(list.toString());
System.out.println("---------");
//binarySearch二分查找
int i=Collections.binarySearch(list, 10);
System.out.println(i);
//copy复制
List<Integer> list2=new ArrayList<Integer>();
for(int i1=0;i1<5;++i1) {
list2.add(0);
}
//该方法要求目标元素容量大于等于源目标
Collections.copy(list2, list);
System.out.println(list2.toString());
//reserve反转
Collections.reverse(list2);
System.out.println(list2.toString());
//shuffle 打乱
Collections.shuffle(list2);
System.out.println(list2.toString());
//补充:list转成数组
Integer[] arr=list.toArray(new Integer[0]);
System.out.println(arr.length);
//补充:数组转成集合
String[] nameStrings= {"tang","he","yu"};
//受限集合,不能添加和删除
List<String> list3=Arrays.asList(nameStrings);
System.out.println(list3);
//注:基本类型转成集合时需要修改为包装类
}
}