集合
集合类的特点:提供一种存储空间可变的的存储模型。
集合只能存储引用类型的数据。
集合:
Collection(单列)和Map(双列)
Collection(单列): List(可重复) Set(不可重复)
Map(双列):HashMap TreeMap 等(实现类)
List(可重复):ArrayList LinkList (实现类)
Set(不可重复):HashSet LinkedHashSet TreeSet(实现类)
(上下是继承关系,父类有的方法,子类都有,还有自己的特有的方法)
1.Collection集合
常用方法:
public boolean add(E e)
: 把给定的对象添加到当前集合中 。public void clear()
:清空集合中所有的元素。public boolean remove(E e)
: 把给定的对象在当前集合中删除。public boolean contains(E e)
: 判断当前集合中是否包含给定的对象。public boolean isEmpty()
: 判断当前集合是否为空。public int size()
: 返回集合中元素的个数。public Object[] toArray()
: 把集合中的元素,存储到数组中。- public Iterator iterator():返回该集合的迭代器。
Iterator接口
集合的专用遍历方式
常用方法:
boolean
hasNext()
如果迭代具有更多元素,则返回true
。E
next()
返回迭代中的下一个元素。使用集合遍历String类型数据
public class CollectionDemo {
public static void main(String[] args) {
Collection<String> strArr = new ArrayList<>();
strArr.add("Hello");
strArr.add("Word");
strArr.add("Java");
strArr.add("J2ee");
Iterator<String> strI = strArr.iterator();
while (strI.hasNext()){ //遍历
String s = strI.next();
System.out.println(s);
}
}
}
在进行集合元素取出时,如果集合中已经没有元素了,还继续使用迭代器的next方法,将会发生java.util.NoSuchElementException没有集合元素的错误。
使用集合遍历学生对象
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo {
public static void main(String[] args) {
Collection<Student> stuArr = new ArrayList<>();
Student s1 = new Student("马瑞",21);
Student s2 = new Student("张骞骞",21);
Student s3 = new Student("谢祥",21);
stuArr.add(s1);
stuArr.add(s2);
stuArr.add(s3);
Iterator<Student> stuI = stuArr.iterator();
while (stuI.hasNext()){
Student s = stuI.next();
System.out.println("姓名:"+s.getName()+" 年龄:"+s.getAge());
}
}
}
1.1List集合
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) :用指定元素替换集合中指定位置的元素,返回值的更新前的元素。
List集合存储学生对象并遍历
List<Student> studentArr = new ArrayList<>();
Student s4 = new Student("马",21);
Student s5 = new Student("谢",21);
Student s6 = new Student("张",21);
studentArr.add(s4);
studentArr.add(s5);
studentArr.add(s6);
Iterator<Student> ii = studentArr.iterator();
while (ii.hasNext()){
Student next = ii.next();
System.out.println("姓名:"+next.getName()+" 年龄:"+next.getAge());
}
并发修改异常
public class ErrorDemo {
public static void main(String[] args) {
List<String> strArr = new ArrayList<>();
strArr.add("Hello");
strArr.add("Word");
strArr.add("Java");
strArr.add("J2ee");
// Iterator<String> strI = strArr.iterator();
// while (strI.hasNext()){
// String s = strI.next();//预期修改值和实际修改值不一致
// if (s.equals("Java")){
// strArr.add("Javaee");
// }
// System.out.println(s);
// }
for (int i = 0; i <strArr.size() ; i++) {
String s = strArr.get(i);
if (s.equals("Java")) {
strArr.add("Javaee");
}
System.out.println(s);
}
}
}
Exception in thread “main” java.util.ConcurrentModificationException
at java.util.ArrayListI t r . c h e c k F o r C o m o d i f i c a t i o n ( A r r a y L i s t . j a v a : 909 ) a t j a v a . u t i l . A r r a y L i s t Itr.checkForComodification(ArrayList.java:909) at java.util.ArrayListItr.checkForComodification(ArrayList.java:909)atjava.util.ArrayListItr.next(ArrayList.java:859)
at cn.taru.day02.time04.ErrorDemo.main(ErrorDemo.java:17)
ConcurrentModificationException并发修改异常
- 当不允许这样的修改时,可以通过检测到对象的并发修改的方法来抛出此异常。
产生原因
迭代器遍历的过程中,通过集合对象修改了集合中元素的长度,造成了迭代器获取元素中判断预期修改值和实际修改值不一致
解决方率
用for循环遍历,然后用集合对象做对应的操作即可
ListIterator(List中特有的迭代器)extend Iterator
Listlterator: 列表迭代器
1.通过List集合的listlterator()方法得到,所以说它是List集合特有的迭代器
2.用于允许程序员沿任一方向遍历列表的列表迭代器,在迭代期间修改列表,并获取列表中迭代器的当前位置
Listlterator中的常用方法:
E next():返回迭代中的下一个元素
boolean hasNext():如果迭代具有更多元素,则返回trueE previous():返回列表中的上一个元素
boolean hasPrevious():如果此列表迭代器在相反方向遍历列表时具有更多元素,则返回true
void add(Ee):将指定的元素插入列表
不演试了
增强for循环
增强for:简化数组和Collection集合的遍历
实现lterable接口的类允许其对象成为增强型for语句的目标
它是JDK5之后出现的,其内部原理是一个lterator迭代器
int[] arr = {1,3,5,8};
for(int i:arr){ //for(元素数据类型 变量名:数组或集合){}
i.sout
}
public class Demo {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("Hello");
list.add("Word");
list.add("Java");
for (String s : list){ //举例
System.out.println(s);
}
}
}
案例(三种遍历方式)
public class ListDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Student s1 = new Student("马瑞",21);
Student s2 = new Student("谢祥",22);
Student s3 = new Student("张骞骞",21);
list.add(s1);
list.add(s2);
list.add(s3);
//第一种:迭代器
ListIterator<Student> it = list.listIterator();
while (it.hasNext()){
Student stu1 = it.next();
System.out.println("姓名:"+stu1.getName()+" 年龄:"+stu1.getAge());
}
System.out.println("-----------");
//第二种:普通for循环
for (int i = 0; i <list.size() ; i++) {
Student stu2 = list.get(i);
System.out.println("姓名:"+stu2.getName()+" 年龄:"+stu2.getAge());
}
System.out.println("-----------");
//第三种:增强for循环
for (Student stu3 : list){
System.out.println("姓名:"+stu3.getName()+" 年龄:"+stu3.getAge());
}
}
}
数组和链表的优缺点(Arraylist, LinkedList)
数组是一种增删慢、查询快的一种数据模型
链表是一种增删快、查询慢的一种数据模型
Arraylist底层数据结构是数组
LinkedList底层数据结构是链表
1.1.1ArrayList
略
1.1.2LinkedList
案例LinkedList集合存储学生对象用三种方式遍历
public class ListDemo {
public static void main(String[] args) {
LinkedList<Student> list = new LinkedList<>();
Student s1 = new Student("马瑞",21);
Student s2 = new Student("谢祥",22);
Student s3 = new Student("张骞骞",21);
list.add(s1);
list.add(s2);
list.add(s3);
//第一种
ListIterator<Student> it = list.listIterator();
while (it.hasNext()){
Student stu1 = it.next();
System.out.println("姓名:"+stu1.getName()+" 年龄:"+stu1.getAge());
}
System.out.println("-----------");
//第二种
for (int i = 0; i <list.size() ; i++) {
Student stu2 = list.get(i);
System.out.println("姓名:"+stu2.getName()+" 年龄:"+stu2.getAge());
}
System.out.println("-----------");
//第三种
for (Student stu3 : list){
System.out.println("姓名:"+stu3.getName()+" 年龄:"+stu3.getAge());
}
}
}
LinkedList的特有方法
方法名 说明
public void addFirst(E e) 在该列表开头插入指定的元素
public void addLast(Ee) 将指定的元素追加到此列表的末尾
publicE getFirst() 返回此列表中的第一个元素
public E getLast() 返回此列表中的最后一个元素
publicEremoveFirst() 从此列表中删除并返回第一个元素
publicE removeLast() 从此列表中删除并返回最后一个元素
1.2Set集合
set集合特点
- 不包含重复元素的集合
- 没有带索引的方法,所以不能使用普通for循环遍历
实现类 HashSet 和 TreeSet
底层数据结构是哈希表
HashSet
- 对集合的迭代次序不作任何保证; 特别是,它不能保证订单在一段时间内保持不变。 这个类允许
null
元素。
哈希值
哈希值:是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值
Object类中有一个方法可以获取对象的哈希值
public int hashCode():返回对象的哈希码值
对象的哈希值特点:
同一个对象多次调用hashCode()方法返回的哈希值是相同的
默认情况下,不同对象的哈希值是不同的。而重写hashCode()方法,可以实现让不同对象的哈希值相同
public class HashDemo {//测试类
public static void main(String[] args) {
Student s1 = new Student("马瑞",21);
Student s2 = new Student("张骞骞",22);
System.out.println(s1.hashCode());
System.out.println(s1.hashCode());
System.out.println("------------");
System.out.println(s2.hashCode());
System.out.println("---------------");
System.out.println("哈哈".hashCode());
System.out.println("呵呵".hashCode());
}
}
public class Student { //实现类
private String name;
private int age;
public Student() {
}
public Student(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 "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return 0;
}
}
HashSet保证元素唯一性源码分析
HashSet集合存储元素:
要保证元素唯一性,需要重写hashCode()和equals()
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-XiXJ4ePx-1613279574383)(C:\Users\86155\AppData\Roaming\Typora\typora-user-images\image-20210212135934249.png)]
先先取余,查看存储位置,在比较哈希值,在比较内容,以链表方式存储
1.2.1HashSet(数组+哈希表)
案例:HashSet集合存储学生对象并遍历
要保证元素唯一性,需要重写hashCode()和equals()
public class HashSetDemo { //测试类
public static void main(String[] args) {
HashSet<Student> set = new HashSet<>();
Student s1 = new Student("马瑞",20);
Student s2 = new Student("谢祥",22);
Student s3 = new Student("张骞骞",20);
Student s4 = new Student("张骞骞",20);
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
for (Student stu:
set) {
System.out.println("姓名:"+stu.getName()+" 年龄:"+stu.getAge());
}
}
}
public class Student { //学生类
private String name;
private int age;
public Student() {
}
public Student(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 "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
}
1.2.2LinkedHashSet(链表+哈希表)
LinkedHashSet集合特点:
- 哈希表和链表实现的Set接口,具有可预测的迭代次序
- 由链表保证元素有序,也就是说元素的存储和取出顺序是一致的
- 保证元素是不重复的
1.2.3TreeSet
TreeSet集合特点:
元素有序,这里的顺序不是指存储和取出的顺序,而是按照一定的规则进行排序,具体排序方式取决于构造方法
TreeSet):根据其元素的自然排序进行排序
TreeSet(Comparator comparator):根据指定的比较器进行排序没有带索引的方法,所以不能使用普通for循环遍历
由于是Set集合,所以不包含重复元素的集合
自然排序Comparable使用:
存储学生对象并遍历,创建TreeSet集合使用无参构造方法
要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
结论
用TreeSet集合存储自定义对象,无参构造方法使用的是自然排序对元素进行排序的自然排序,就是让元素所属的类实现Comparable接口,重写compareTo(T o)方法重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写
public class Student implements Comparable<Student> { //学生类继承Comparable接口
//补充
@Override
public int compareTo(Student s) {//******************************重难点**************************
//return 0 重复
//return 1 升序
//return -1 降序
// int sum = this.age-s.age; 主要条件//this代表s2,s代表s1
int num = this.age-s.age;
int num2 = num ==0?(this.name.compareTo(s.name)):num;//this.name.compareTo(s.name)次要条件
return num2;
}
}
public class TreeSetDemo { //测试类
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>();
Student s1 = new Student("马瑞",20);
Student s2 = new Student("谢祥 ",22);
Student s3 = new Student("张骞骞",20);
// Student s4 = new Student("张骞骞",20);
set.add(s1);
set.add(s2);
set.add(s3);
for(Student s : set){
System.out.println(s.getName()+s.getAge());
}
// int i = s1.getName().compareTo(s2.getName()); //String类的方法,按字典顺序比较两个字符串。
// System.out.println(i);
}
}
ClassCastException
- 抛出表示代码尝试将对象转换为不属于实例的子类。
比较器排序Comparator的使用
存储学生对象并遍历,创建TreeSet集合使用带参构造方法
要求:按照年龄从小到大排序,年龄相同时,按照姓名的字母顺序排序
结论
用TreeSet集合存储自定义对象,带参构造方法使用的是比较器排序对元素进行排序的
比较器排序,就是让集合构造方法接收Comparator的实现类对象,重写compare(T o1,T o2)方法
重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写
public class ComparatorDemo {
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() {//构造方法
@Override //TreeSet(Comparator<? super E> comparator)
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
int num2 = num == 0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
Student s1 = new Student("马瑞",20);
Student s2 = new Student("谢祥",22);
Student s3 = new Student("张骞骞",20);
Student s4 = new Student("张骞骞",20);
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
for (Student stu:
set) {
System.out.println("姓名:"+stu.getName()+" 年龄:"+stu.getAge());
}
}
}
案例TreeSet集合成绩排序
学生类:姓名,数学,语文
要求:按数学和语文的总分排名
public class Student { //学生类
private String name;
private int chinese;
private int math;
public Student() {
}
public Student(String name, int chinese, int math) {
this.name = name;
this.chinese = chinese;
this.math = math;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return chinese;
}
public void setChinese(int chinese) {
this.chinese = chinese;
}
public int getMath() {
return math;
}
public void setMath(int math) {
this.math = math;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", chinese=" + chinese +
", math=" + math +
'}';
}
}
public class TreeSetDemo { //测试类 比较器排序
public static void main(String[] args) {
TreeSet<Student> set = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int num = (s2.getChinese()+s2.getMath())-(s1.getChinese()+s1.getMath());//排序赋值
return num;
}
});
Student s1 = new Student("马瑞",86,89);
Student s2 = new Student("谢祥",85,92);
Student s3 = new Student("张骞骞",93,96);
Student s4 = new Student("李四",92,90);
set.add(s1);
set.add(s2);
set.add(s3);
set.add(s4);
for (Student s : set){
System.out.println("姓名:"+s.getName()+" 语文:"+s.getChinese()+" 数学"+s.getMath());
}
}
}
案例HashSet(不重复的随机数)
要求:获取10个1-20的不重复随机数,输出。
public class RandomDemo {
public static void main(String[] args) {
HashSet<Integer> set = new HashSet<>();
Random r = new Random();
while (set.size()<10){
int i = r.nextInt(20)+1;
set.add(i);
}
for (Integer i : set){
System.out.println(i);//自动拆箱
}
}
}
泛型
泛型;是JDK5中引入的特性,它提供了编译时类型安全检测机制,该机制允许在编译时检测到非法的类型它的本质是参数化类型,也就是说所操作的数据类型被指定为一个参数
一提到参数,最熟悉的就是定义方法时有形参,然后调用此方法时传递实参。那么参数化类型怎么理解呢?
就是将类型由原来的具体的类型参数化,然后在使用/调用时传入具体的类型
这种参数类型可以用在类、方法和接口中,分别被称为泛型类、泛型方法、泛型接口
泛型的好处:
把运行时期的问题提前到了编译期间
避免了强制类型转换
泛型类
泛型类格式
public class 类名 {} (T,E,K,V)
public class Student{}
public class Generic<T> { //泛型类
private T t;
public Generic() {
}
public Generic(T t) {
this.t = t;
}
public T getT() {
return t;
}
public void setT(T t) {
this.t = t;
}
}
public class GenericDemo { //测试类
public static void main(String[] args) {
Generic<String> sg1 = new Generic<>();
sg1.setT("张骞骞");
Generic<Integer> sg2 = new Generic<>();
sg2.setT(21);
System.out.println(sg1.getT()+" "+sg2.getT());
}
}
泛型方法
格式
修饰符<类型>返回值类型 方法名(类型 变量名){ }
public void show(T t){ }
public class Generic02 {
public<T> void show(T t){ //泛型方法
System.out.println(t);
}
}
public class GenericDemo02 { //测试类
public static void main(String[] args) {
Generic02 g = new Generic02();
g.show("谢祥");
g.show(21);
g.show(21.23);
}
}
泛型接口
泛型接口的定义格式:
格式:修饰符interface接口名<类型>{ }
范例:publicinterface Generic{ }
public interface Generic<T> { //泛型接口
public abstract void show(T t);
}
public class GenericImpl<T> implements Generic<T> {//实现类
@Override
public void show(T t) {
System.out.println(t);
}
}
public class GenericDemo { //测试类
public static void main(String[] args) {
Generic<String> sg1 = new GenericImpl<>();
sg1.show("谢祥");
Generic<Integer> ig1 = new GenericImpl<>();
ig1.show(21);
}
}
类型通配符
为了表示各种泛型List的父类,可以使用类型通配符
类型通配符:<?>
List<?>:表示元素类型未知的List,它的元素可以匹配任何的类型
这种带通配符的List仅表示它是各种泛型List的父类,并不能把元素添加到其中
如果说我们不希望List<?>是任何泛型List的父类,只希望它代表某一类泛型List的父类,可以使用类型通配符的上限
类型通配符上限:<? extends类型>
List<? extends Number> :它表示的类型是Number或者其子类型
除了可以指定类型通配符的上限,我们也可以指定类型通配符的下限
类型通配符下限:<? super类型>
List<? super Number> :它表示的类型是Number或者其父类型
举例
java.lang.Object //继承关系
java.lang.Number
java.lang.Integer
public class Demo {
public static void main(String[] args) {
//类型通配符<?>
List<?> list1 = new ArrayList<Object>();
List<?> list2 = new ArrayList<Number>();
List<?> list3 = new ArrayList<Integer>();
//类型通配符上限:<? extends类型>
List<? extends Number> list4 = new ArrayList<Number>();
List<? extends Number> list5 = new ArrayList<Integer>();
// List<? extends Number> list6 = new ArrayList<Object>();
//类型通配符下限:<? super类型>
List<? super Number> list7 = new ArrayList<Object>();
List<? super Number> list8 = new ArrayList<Number>();
// List<? super Number> list9 = new ArrayList<Integer>();
}
}
可变参数
可变参数又称参数个数可变,用作方法的形参出现,那么方法参数个数就是可变的了
格式: 修饰符返回值类型方法名(数据类型…变量名){}
范例: publicstatic int sum(int… a){ }
可变参数注意事项
1.这里的变量其实是一个数组
2.如果一个方法有多个参数,包含可变参数,可变参数要放在最后
public class SumDemo {
public static void main(String[] args) {
System.out.println(getSum(10,20));
System.out.println(getSum(10,20,30));
System.out.println(getSum(10,20,30,40));
}
public static int getSum(int ...a){ //get(int b, ...a){}
int sum = 0;
for (Integer i : a){
sum += i;
}
return sum;
}
}
可变参数的使用
1.Arrays工具类中有一个静态方法:
public static List asList(T… a):返回由指定数组支持的固定大小的列表
返回的集合不能做增删操作,可以做修改操作
2.List接口中有一个静态方法:
public static List of(E… elements):返回包含任意数呈元素的不可变列表
的集合不能做增删改操作
3.Set接口中有一个静态方法:
public static Set of(E… elements):返回一个包含任意数量元素的不可变集合
在给元素的时候,不能给重复的元素
返回的集合不能做增删操作,没有修改的方法
public class ListDemo {
public static void main(String[] args) {
List<String> list1 = Arrays.asList("Hello", "Word", "Java");
// list1.add("j2ee");//UnsupportedOperationException 抛出以表示不支持请求的操作。
list1.set(1,"javaee");
// list1.remove(0);//UnsupportedOperationException
System.out.println(list1);
}
}
//其他如下
2.Map集合
Map集合概述
lnterface MapK:键的类型;V:值的类型
将键映射到值的对象;不能包含重复的键;每个键可以映射到最多一个值举例:学生的学号和姓名
001 马瑞
002 谢祥
003 张骞骞
创建Map集合的对象
1.多态的方式
2.具体的实现类HashMap
常用方法
clear()
从该地图中删除所有的映射(可选操作)。
isEmpty()
如果此地图不包含键值映射,则返回true
。
put(K key, V value)
将指定的值与该映射中的指定键相关联(可选操作)。 (键第一次出现是添加,第二次出现是修改)
remove(Object key)
如果存在(从可选的操作),从该地图中删除一个键的映射。boolean
containsKey(Object key)
如果此映射包含指定键的映射,则返回true
。boolean
containsValue(Object value)
如果此地图将一个或多个键映射到指定的值,则返回true
size()
返回此地图中键值映射的数量。
例:Map<String,String> map = new HashMap<>();(Hash保证键的唯一性)
Map<String,String>map = new TreeMap<>();(可排序)
Map集合获取功能
v get(Object key) 根据键获取值
Set keySet() 获取所有摊的集合
Collection values() 获取所有值的集合
Set<Map.Entry<K,V> > entrySet() 获取所有键值对对象的集合
public class MapDemo {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1,"马瑞");
map.put(2,"谢祥");
map.put(3,"张骞骞");
String s = map.get(1);//根据键获取值
System.out.println(s);
Set<Map.Entry<Integer, String>> entries = map.entrySet();//获取所有键值对对象的集合
for (Map.Entry<Integer, String> entry : entries){
System.out.println(entry);
}
Set<Integer> keySet = map.keySet();//获取所有键
for (Integer i : keySet){
System.out.println(i);
Collection<String> values = map.values();//获取所有值
Iterator<String> ii = values.iterator();
while (ii.hasNext()){
String s1 = ii.next();
System.out.println(s1);
}
}
}
}
Map集合的遍历(1)(先获得丈夫集合,根据丈夫集合获取妻子)
我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合
遍历思路
1.把所有的丈夫给集中起来
2.遍历丈夫的集合,获取到每一个丈夫根据丈夫去找对应的妻子
转换为Map集合中的操作:
1.获取所有键的集合。用keySet()方法实现
2.遍历键的集合,获取到每一个键。
3.用增强for实现根据键去找值。用get(Object key)方法实现
public class MapDemo02 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1,"马瑞");
map.put(2,"谢祥");
map.put(3,"张骞骞");
Set<Integer> keySet = map.keySet();
for (Integer key : keySet){
String value = map.get(key);
System.out.println(key+","+value);
}
}
}
Map集合的遍历(2)(先获得结婚证集合,根据结婚证集合获取结婚证集合对象)
我们刚才存储的元素都是成对出现的,所以我们把Map看成是一个夫妻对的集合
遍历思路
1.获取所有结婚证的集合
2.遍历结婚证的集合,得到每一个结婚证根据结婚证获取丈夫和妻子
转换为Map集合中的操作:
1.获取所有键值对对象的集合
Set<Map.Entry<K,V>> entrySet(:获取所有键值对对象的集合
2.遍历键值对对象的集合,得到每一个键值对对象
用增强for实现,得到每一个Map.Entry
3.根据键值对对象获取键和值
用getKey0得到键
用getValue0得到值
public class MapDemo03 {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1,"马瑞");
map.put(2,"谢祥");
map.put(3,"张骞骞");
Set<Map.Entry<Integer, String>> set = map.entrySet();
// System.out.println(set); //[1=马瑞, 2=谢祥, 3=张骞骞]"结婚证集合"
for(Map.Entry<Integer, String> is : set){
//根据结婚证集合获取结婚证集合对象
System.out.println(is.getKey()+","+is.getValue());
}
}
}
HashMap存储学生对象并遍历(需求1)
需求:
创建一个HashMap集合,键是学号(String),值是学生对象(Student)。存储三个键值对元素,并遍历
public class HashMapDemo { //测试类
public static void main(String[] args) {
Map<String,Student> map = new HashMap<>();
Student s1 = new Student("马瑞",20);
Student s2 = new Student("谢祥",21);
Student s3 = new Student("张骞骞",22);
map.put("5011218312",s1);
map.put("5011218313",s2);
map.put("5011218314",s3);
//方式一:键值对对象找值
Set<Map.Entry<String, Student>> set = map.entrySet();
for (Map.Entry<String, Student> ss : set){
System.out.println("学号:"+ss.getKey()+" 姓名:"+ss.getValue().getName()
+" 年龄:"+ss.getValue().getAge());
}
System.out.println("---------------");
//方式二:键值对对象找值
Set<String> keySet = map.keySet();
for (String key:keySet
) {
Student value = map.get(key);
System.out.println("学号:"+key+" 姓名:"+value.getName()+" 年龄:"+value.getAge());
}
}
//学生类(略)
HashMap存储学生对象并遍历(需求2)
需求:
创建一个HashMap集合,键是学生对象(Student),值是居住地(String)。存储多个键值对元素,并遍历。
要求保证键的唯一性:如果学生对象的成员变量值相同,我们就认为是同一个对象(重写两个方法)**
public class HashMapDemo02 {
public static void main(String[] args) {
Map<Student,String> map = new HashMap<>();
Student s1 = new Student("马瑞",20);
Student s2 = new Student("谢祥",21);
Student s3 = new Student("张骞骞",22);
Student s4 = new Student("张骞骞",22);
map.put(s1,"马来西亚");
map.put(s2,"伦敦");
map.put(s3,"巴塞罗那");
map.put(s4,"维多利亚");
Set<Student> keySet = map.keySet();
for (Student key : keySet){
String value = map.get(key);//根据键找值
String name = key.getName();
int age = key.getAge();
System.out.println(" 姓名:"+name+" 年龄:"+age+" 居住地"+value);
}
}
}
//学生类重写public boolean equals(Object o)
// public int hashCode()
ArrayList集合存储HashMap元素并遍历
需求:
创建一个Araylist集合,存储三个元素,每一个元素都是HashMap,每一个HashMap的腱和值都是String,并遍历
思路:
1.创建ArrayList集合
2.创建HashMap集合,并添加键值对元素
3.把HashMap作为元素添加到ArrayList集合
4.遍历ArrayList集合
public class ArrayMapDemo { ***************************//多理解几遍************************************
public static void main(String[] args) {
ArrayList<HashMap<String,String>> array = new ArrayList<>();
HashMap<String, String> hm1 = new HashMap<>();
hm1.put("张三","李四");
HashMap<String, String> hm2 = new HashMap<>();
hm2.put("王二麻子","张骞骞");
HashMap<String, String> hm3 = new HashMap<>();
hm3.put("马瑞","谢祥");
array.add(hm1);
array.add(hm2);
array.add(hm3);
for (HashMap<String,String> hm : array){ //遍历ArrayList
Set<Map.Entry<String, String>> entries = hm.entrySet();//获取键值对集合
for (Map.Entry<String, String> mm:entries){//获取键值对集合对象
System.out.println(mm.getKey()+" "+mm.getValue());
}
}
}
}
HashMap集合存储ArrayList元素并遍历
需求:
创建一个HashMap集合,存储三个键值对元素,每一个键值对元素的键是String,值是ArrayList,
每一个ArrayList的元素是String,并遍历
思路;
1.创建HashMap集合
2.创建ArrayList集合,并添加元素
3.把ArrayList作为元素添加到HashMap集合
4.遍历HashMap集合
public class MapArrayDemo {
public static void main(String[] args) {
HashMap<String,ArrayList<String>> hm = new HashMap<>();
ArrayList<String> array1 = new ArrayList<>();
array1.add("诸葛亮");
array1.add("赵云");
ArrayList<String> array2 = new ArrayList<>();
array2.add("唐僧");
array2.add("孙悟空");
ArrayList<String> array3 = new ArrayList<>();
array3.add("武松");
array3.add("鲁智深");
hm.put("三国演义",array1);
hm.put("西游记",array2);
hm.put("水浒传",array3);
Set<Map.Entry<String, ArrayList<String>>> entrySet = hm.entrySet();//根据键值对对象获取
for (Map.Entry<String, ArrayList<String>> mm : entrySet){
ArrayList<String> list = mm.getValue();
System.out.println(mm.getKey() + " :");
for (String s : list){
System.out.println(s);
}
}
}
}
统计字符串中每个字符出现的次数
需求:
键盘录入一个字符串,要求统计字符串中每个字符串出现的次数。
举例:键盘录入“aababcabcdabcde"
在控制台输出:“a(5)b(4)c(3)d(2)e(1)"
思路;
键盘录入—个字符串
创建HashMap集合,键是Character,值是Integer3遍历字符串,得到每一个字符
拿得到的每一个字符作为键到HashMap集合中去武对应的值,看其返回值
如果返回值是null:说明该字符在HashMap集合中不存在,就把该字符作为键,1作为值存储
如果返回值不是null:说明该字符在HashMap集合中存在,把该值加1,然后重新存储该字符和对应的值⑤遍历HashMap集合,得到腱 和值,按照要求进行拼接
输出结果
public class StringTreeMapDemo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入字符串:");
String s = sc.next();
TreeMap<Character, Integer> tm = new TreeMap<>();
for (int i = 0; i < s.length(); i++) {
char key = s.charAt(i); //遍历字符串
Integer value = tm.get(key); //根据键获取值
if (value == null) {
tm.put(key, 1); //为null,第一次存储
} else {
value++;
tm.put(key,value);//第二次存储,修改值
}
}
StringBuilder sb = new StringBuilder();//拼接字符串对象
Set<Character> keySet = tm.keySet();//获取键的集合
for (Character key :keySet) { //遍历键
Integer value = tm.get(key); //根据键获取值
sb.append(key).append("(").append(value).append(")");//拼接
}
String s1 = sb.toString();//StringBuilder类型转String类型
System.out.println(s1);
}
}
Collections概述和使用
●是针对集合操作的工具类
Collections类的常用方法
public static <T extends Comparable<? super T>> void sort(List list):将指定的列表按升序排序
public static void reverse(List<?> list):反转指定列表中元素的顺序
public static void shuffle(List<?> list):使用默认的随机源随机排列指定的列表
ArrayList集合存储学生对象并排序
public class ArrayListDemo {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
Student s1 = new Student("marui",21);
Student s2 = new Student("xiexiao",22);
Student s3 = new Student("zhangqianqian",21);
list.add(s1);
list.add(s2);
list.add(s3);
Collections.sort(list, new Comparator<Student>() { //Collections工具类的方法,参数:list,接口
@Override
public int compare(Student s1, Student s2) {
int num = s1.getAge() - s2.getAge();
int num2 = num ==0?s1.getName().compareTo(s2.getName()):num;
return num2;
}
});
for (Student s : list){
System.out.println(s.getName()+", "+s.getAge());
}
}
}
案例斗地主
需求:
通过程序实现斗地主过程中的洗牌,发牌和看牌
思路:
创建一个牌盒,也就是定义一个集合对象,用ArrayList集合实现
往牌盒里面装牌
洗牌,也就是把牌打撒,用Collections的shuffle()方法实现
发牌,也就是遍历集合,给三个玩家发牌
看牌,也就是三个玩家分别遍历自己的牌
public class DouDiZhuDemo {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
String[] colors = {"♦", "♣", "♥", "♠"};
String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
for (String c : colors) {
for (String n : numbers) {
list.add(c + n);
}
}
list.add("大王");
list.add("小王");
Collections.shuffle(list);
ArrayList<String> marui = new ArrayList<>();
ArrayList<String> xiexiang = new ArrayList<>();
ArrayList<String> zhangqianqian = new ArrayList<>();
ArrayList<String> dipai = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
String poker = list.get(i);
if (i >= list.size() - 3) {
dipai.add(poker);
} else if (i % 3 == 0) {
marui.add(poker);
} else if (i % 3 == 1) {
xiexiang.add(poker);
} else if (i % 3 == 2) {
zhangqianqian.add(poker);
}
}
lookPoker("马瑞", marui);
lookPoker("谢祥", xiexiang);
lookPoker("张骞骞", zhangqianqian);
lookPoker("底牌", dipai);
}
public static void lookPoker(String name, ArrayList<String> array) {
System.out.println(name + "的牌是:");
for (String poker : array) {
System.out.print(poker + " ");
}
System.out.println();
}
}