集合
为什么使用集合框架?
如果并不知道程序运行时会需要多少对象,或者需要更复杂方式存储对象–可以使用Java集合框架
Java集合框架包含的内容
Java集合框架提供了一套性能优良、使用方便的接口和类,它们位于java.util包中
Iteratior:接口类
ArrayList:具体实现类
Collection:所有Java集合框架的父接口
Collections:操作集合的工具类
Utilities:算术类。提供了对集合进行排序、遍历等多种算法实现
Collection接口:
Collection接口存储一组:不唯一、无序的接口
List接口存储一组:不唯一、有序(插入顺序)的对象
Set接口存储一组:唯一、无序的对象
Map接口存储一组链值对象,提供Key到value的映射
Collection接口常用通用方法还有:
clear() 、 isEmpty() 、 iterator() 、toArray()
List接口:的实现类
ArrayList实现了长度可变的数组,在内存中分配连续的空间。遍历元素和随机访问元素的效率比较高
LinkedList采用链表存储。插入、删除元素时效率比较高
ArrayList常用方法
方法名 | 说明 |
---|---|
bollean add(Object o) | 在列表的末尾顺序添加元素,起始索引位置从0开始 |
void add(int index,Object o) | 在指定的索引位置添加元素。索引位置必须介于0和列表中元素个数之间 |
int size() | 返回列表中的元素个数 |
Object fet(int index) | 返回指定索引位置处的元素。取出的元素是Object类型,使用前需要进行强制类型转换 |
boolean contains(Object o) | 判断列表中是否存在指定元素 |
boolean remove(Object o) | 从列表中删除元素 |
Object remove(int index) | 从列表中删除指定位置元素,起始索引位置从0开始 |
LinkedList常用方法
确定存储方式
1.LinkedList类是List接口的一个具体实现类
2.LinkedList类用于创建链表数据结构
3.插入或者删除元素时,它提供更好的性能
具体实现
方法名 | 说明 |
---|---|
void addFirst(Object o) | 在列表的首部添加元素 |
void addLast(Object o) | 在列表的末尾添加元素 |
Object getFirst() | 返回列表中的第一个元素 |
Object getLast() | 返回列表中的最后一个元素 |
Object removeFirst() | 删除并返回列表中的第一个元素 |
Object removeLast() | 删除并返回列表中的最后一个元素 |
Set接口:
HashSet是Set接口常用的实现类
Set中存放对象的引用
Set set = new HashSet();
String s1 = new String("java");
String s2 = s1;
String s3 = new String("JAVA");
set.add(s1);
set.add(s2);
set.add(s3);
System.out.println(set.size());
Set接口如何判断加入对象是否已经存在?
采用的对象的equals()方法比较两个对象是否相等
Set接口不存在get()方法
newsTitleSet.get(0);
迭代器Iterator
如何遍历Set集合?
方法一:通过迭代器Iterator实现遍历
获取Iterator:Collection接口的iterator()方法
Iterator的方法
boolean hasNext():判断是否存在另一个可访问的元素
Object next():返回要访问的下一个元素
方法二:增强型for循环
Map接口
与Collection没有继承关系,是一个独立的接口
Map接口专门处理键值映射数据的存储,可以根据键值实现对值的操作
最常见的实现类是HashMap
import java.util.HashMap;
import java.util.Map;
//存储国家的英文简称(键) 国家全程(值) (键-值对)
public class MapDemo {
public static void main(String[] args) {
Map countries = new HashMap();
//往Map集合中添加键值对
countries.put("CN", "中华人民共和国");
countries.put("RU", "俄罗斯联邦");
countries.put("FR", "法兰西共和国");
countries.put("US", "美利坚共和国");
//获取Map的元素组数
System.out.println(countries.size());
//通过某个键获取对应的值
String cnStr = (String)countries.get("CN");
System.out.println(cnStr);
//判断Map中是否包含某个键
boolean flag = countries.containsKey("US");
System.out.println("集合中是否包含us?"+flag);
//删除特定键对应的键值对
countries.remove("US");
System.out.println(countries.size());
flag = countries.containsKey("US");
System.out.println("集合中是否包含US?"+flag);
//分别显示Map中键集、值集 和键值对集
System.out.println(countries.keySet());
System.out.println(countries.values());
System.out.println(countries);
//清空
countries.clear();
if(countries.isEmpty()) {
System.out.println("Map数据已经清空!");
}
}
}
Map接口常用方法
方法名 | 说明 |
---|---|
Object put(Object key,Object val) | 以 " 键 - 值 " 对的方式进行存储 |
Object get(Object key) | 根据键返回相关联的值 , 如果不存在指定的键 , 返回null |
Object remove(Object key) | 删除由指定的键映射的 " 键 - 值对 " |
int size( ) | 返回元素个数 |
Set keySet( ) | 返回键的集合 |
Collection values( ) | 返回值的集合 |
boolean containsKey(Object key) | 如果存在由指定的键映射的 " 键 - 值对 " , 返回true |
遍历Map
泛型
如何解决一下强制类型转换时容易出现的异常问题?
List的get(int index)方法获取元素
Map的get(Object key)方法获取元素
Iterator的next()方法获取元素
通过泛型
JDK5.0使用泛型改写了集合框架中的所有接口和类
将对象的类型作为参数 , 指定到其他类或者方法上 , 从而保证类型转换的安全性和稳定性
本质是参数化类型
泛型集合可以约束集合内的元素类型
典型泛型集合ArrayList 、HashMap<K,V>
、<K,V>表示该泛型集合中的元素类型
泛型集合中的数据不再转换为Object
Collections
Collections算法类
Java集合框架将针对不同数据结构算法的实现都保存在工具类中
Collections类定义了一系列用于操作集合的静态方法
Collections类常用方法
-
Collections和Collection不同 , 前者是集合的操作类 , 后者是集合接口
-
Collections提供的常用静态方法
(1)sort( ):排序
(2)binarySearch( ):查找
(3)max( ) \ min( ):查找最大值 \ 最小值
import java.util.*; public class test{ public static void main(String[] args) }
import java.util.*;
public class Test {
public static void main(String[] args) {
System.out.println("---------方法一---------");
List numList = Arrays.asList(6,5,9,1,10,7);
for(Object obj : numList) {
System.out.println(obj);
}
System.out.println("---------方法二---------");
List numList1 = new ArrayList();
numList1.add(6);
numList1.add(5);
numList1.add(9);
numList1.add(1);
numList1.add(10);
numList1.add(7);
for(Object obj : numList1) {
System.out.println(obj);
}
System.out.println("---------排序---------");
Collections.sort(numList);
System.out.println("排序后输出");
for(Object obj : numList) {
System.out.println(obj);
}
System.out.println("---------泛型---------");
List<Integer> numList3 = new ArrayList<Integer>();
numList3.add(6);
numList3.add(5);
numList3.add(9);
numList3.add(1);
numList3.add(10);
numList3.add(7);
System.out.println("最大值是");
System.out.println(Collections.max(numList3));
}
}
Collections排序
1.Collections类可以对集合进行排序、查找和替换操作
2.实现一个类的对象之间比较大小 , 该类要实现Comparable接口
(1)重写compareTo( )方法
-测试类
import java.util.*;
public class CollectionsPaixu {
public static void main(String[] args) {
List<Student> stuList = new ArrayList<Student>();
stuList.add(new Student("张三","男",18));
stuList.add(new Student("张三2","男",19));
stuList.add(new Student("张三3","男",21));
stuList.add(new Student("张三4","男",16));
for(Student s :stuList) {
System.out.println(s);
}
System.out.println("--------------------------");
Collections.sort(stuList);
for(Student s :stuList) {
System.out.println(s);
}
}
}
-学生类
/**
* 学生类
* @author huang
*
*/
public class Student implements Comparable<Student>{
private String name;
private String sex;
private int age;
public Student(String name, String sex, int age) {
super();
this.name = name;
this.sex = sex;
this.age = age;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
}
@Override
public int compareTo(Student s) {
if(this.age == s.age) {
return 0;
}else if(this.age > s.age) {
return 1;
}else {
return -1;
}
}
}
案例
案例一
ArrayList集合类
新闻管理系统,需求如下
1.可以储存各类新闻标题(包括ID、名称、创建者)
2.可以获取各类新闻标题的总数
3.可以逐条打印每条新闻标题的名称
-测试类
package teat1;
import java.util.*;
public class test1 {
public static void main(String[] args) {
ArrayList NewsList = new ArrayList();
NewsList.add(new News(1,"新闻标题1","作者1"));
NewsList.add(new News(2,"新闻标题2","作者2"));
NewsList.add(new News(3,"新闻标题3","作者3"));
System.out.println("新闻标题的总数:"+NewsList.size());
Iterator itor = NewsList.iterator();
while(itor.hasNext()){
System.out.println(itor.next());
}
}
}
-新闻类
package teat1;
public class News {
private int id;
private String title;
private String author;
public News(int id, String title, String author) {
super();
this.id = id;
this.title = title;
this.author = author;
}
public News() {
super();
// TODO Auto-generated constructor stub
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return this.getTitle();
}
}
案例二
-测试类
package teat1;
import java.util.*;
public class Test {
public static void main(String[] args) {
Map<String,Student> students = new HashMap<String,Student>();
students.put("Jack",new Student("李明","男"));
students.put("Tom",new Student("张三","男"));
students.put("Alex",new Student("李四","男"));
System.out.println("Jack"+students.get("Jack"));
}
}
-学生类
package teat1;
public class Student {
private String name;
private String sex;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "对应的学员姓名是"+this.getName()+"性别是"+this.getSex();
}
}
案例三
![CHAPTER-11 集合-3](D:\JAVA COURSE\MD JAVA\CHAPTER-11 集合-3.png)![CHAPTER-11 集合-4](D:\JAVA COURSE\MD JAVA\CHAPTER-11 集合-4.png)package hw1;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
Map country = new HashMap();
country.put("US", "美利坚共和国");
country.put("RU", "俄罗斯共和国");
country.put("CN", "中华人民共和国");
country.put("FR", "法兰西共和国");
String cnStr = (String)country.get("CN");
System.out.println("CN对应的国家是: "+country.get("CN"));
System.out.println("Map中共有"+country.size()+"组数据");
boolean flag = country.containsKey("FR");
System.out.print("Map中包含FR的key吗?"+flag);
System.out.println();
country.remove("FR");
boolean flag1 = country.containsKey("FR");
System.out.print("Map中包含FR的key吗?"+flag1);
System.out.println();
System.out.println(country.keySet());
System.out.println(country.values());
System.out.println(country);
country.keySet();
country.remove(country.keySet());
country.clear();
System.out.println("已清空Map中数据!");
// country.remove(country, country);
// for(Object obj : country.keySet()) {
// System.out.println(country.get(obj));
// }
}
}
案例四
package hw2;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class Test {
public static void main(String[] args) {
Map country = new HashMap();
country.put("US", "美利坚共和国");
country.put("RU", "俄罗斯共和国");
country.put("CN", "中华人民共和国");
country.put("FR", "法兰西共和国");
String cnStr = (String)country.get("CN");
System.out.println("CN对应的国家是: "+country.get("CN"));
System.out.println("Map中共有"+country.size()+"组数据");
boolean flag = country.containsKey("FR");
System.out.print("Map中包含FR的key吗?"+flag);
System.out.println();
country.remove("FR");
boolean flag1 = country.containsKey("FR");
System.out.print("Map中包含FR的key吗?"+flag1);
System.out.println();
System.out.println(country.keySet());
System.out.println(country.values());
System.out.println(country);
country.keySet();
country.remove(country.keySet());
country.clear();
System.out.println("已清空Map中数据!");
System.out.println("-----------------------------------");
System.out.println("---------第二题---------");
Set keys = country.keySet();
System.out.println("---------Iterator---------");
Iterator itor = keys.iterator();
while(itor.hasNext()) {
String key = (String)itor.next();
String vlaue = (String)country.get(key);
System.out.println(key+"--"+vlaue);
}
System.out.println("---------增强型for---------");
for(Object obj : keys) {
String key = (String)obj;
String value = (String)country.get(key);
System.out.println(key+"--"+value);
}
System.out.println("---------键值对---------");
System.out.println(country.keySet());
System.out.println(country.values());
System.out.println(country);
}
}
案例五
-测试类
package hw3;
import java.util.*;
/**
* 测试类
* @author huang
*
*/
public class Test {
public static void main(String[] args) {
Student stu1 = new Student("李明","男");
Student stu2 = new Student("张三","女");
Student stu3 = new Student("王五","男");
Map stu = new HashMap();
stu.put("Jack", stu1);
stu.put("Michael", stu2);
stu.put("Tommy", stu3);
Set set = stu.entrySet();
for(Object obj : set) {
Map.Entry s = (Map.Entry)obj;
String key = (String)s.getKey();
Student student = (Student)s.getValue();
System.out.println(key+"对应的学员姓名是:"+student.getName()+";性别是:"+student.getSex());
}
}
}
-学生类
package hw3;
/**
* 学员类
* @author huang
*
*/
public class Student {
private String name;//姓名
private String sex;//性别
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "Student [name=" + name + ", sex=" + sex + "]";
}
}
案例六
-测试类
package teat1;
import java.util.*;
public class Test {
public static void main(String[] args) {
Map<String,Student> students = new HashMap<String,Student>();
students.put("Jack",new Student("李明","男"));
students.put("Tom",new Student("张三","男"));
students.put("Alex",new Student("李四","男"));
System.out.println("Jack"+students.get("Jack"));
}
}
-学生类
package teat1;
public class Student {
private String name;
private String sex;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "对应的学员姓名是"+this.getName()+"性别是"+this.getSex();
}
}
dents.put(“Jack”,new Student(“李明”,“男”));
students.put(“Tom”,new Student(“张三”,“男”));
students.put(“Alex”,new Student(“李四”,“男”));
System.out.println("Jack"+students.get("Jack"));
}
}
-学生类
```JAVA
package teat1;
public class Student {
private String name;
private String sex;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "对应的学员姓名是"+this.getName()+"性别是"+this.getSex();
}
}