java笔记整理:集合
目录
集合
- 概念:对象的容器,定义了对多个对象进行操作的常用方法,实现了对对象常用的操作,类似数组的功能
- 和数组的区别:
- 1.数组长度固定,集合长度不固定
- 2.数组可以存储基本类型和引用类型,集合只能存储引用类型
- 位置:java.util.*;
Collection体系集合
Collection父接口
- 特点:该体系结构的根接口,代表一组任意类型对象,无序、无下标、不能重复,’称为“集合”
- 两个子接口:
- List:有序、有下标、元素可重复
- set:无序、无下标、元素不能重复
- 方法:
- add(Object obj) //添加一个对象
- addAll(Collection c) //将一个集合中的所有对象添加到此集合中
- clear() //清空此集合中的所有对象
- contains(Object o) //检查此集合中是否包含o对象
- equals(Object o) //比较此集合中是否与指定对象相等
- isEmpty() //判断此集合是否为空
- remove(Object o) //在此集合中移除o对象
- size() //返回此集合中的元素个数
- toArray() //将此集合转换成数组
package Collectionproject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
*Collection接口的使用
* (1)添加元素
* (2)删除元素
* (3)遍历元素
* (4)判断
**/
public class Demo01 {
public static void main(String[] args) {
//创建集合
Collection collection = new ArrayList();
//t添加元素
collection.add("苹果");
collection.add("西瓜");
collection.add("橘子");
System.out.println("元素个数"+collection.size());
System.out.println(collection.toString());
//删除元素
// collection.remove("西瓜");
// System.out.println("元素的个数:"+collection.size());
//遍历元素【重点!!!】
//(1)使用增强for(foreach)
System.out.println("-----------------------------");
for (Object object:collection) {
System.out.println(object);
}
//(2)迭代器(迭代器专门用来遍历集合的一种方式)Iterator接口
/*
Iterator三种方法:
(1)hasNext()有没有下一个元素
(2)Next()获取下一个元素
(3)remove()删除当前的元素
*/
System.out.println("-----------------------------");
Iterator it = collection.iterator();
while(it.hasNext()){
String str = (String)it.next();
System.out.println(str);
it.remove();
}
System.out.println("元素个数:"+collection.size());
}
}
举例:保存学生信息
package Collectionproject;
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 +
'}';
}
}
package Collectionproject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* Collection的使用:保存学生信息
*/
public class Demo02 {
public static void main(String[] args) {
//新建Collection对象
Collection collection = new ArrayList();
student s1 = new student("张三",18);
student s2 = new student("李四",20);
student s3 = new student("王五",19);
student s4 = new student("赵六",22);
//添加
collection.add(s1);
collection.add(s2);
collection.add(s3);
collection.add(s4);
System.out.println(collection.toString());
//删除
collection.remove(s1);
System.out.println(collection.toString());
//遍历
//(1)增强for
for (Object obj:collection) {
student s = (student)obj;
System.out.println(s.toString());
}
//(2)迭代器
Iterator it = collection.iterator();
while(it.hasNext()){
student stu = (student) it.next();
System.out.println(stu.toString());
}
//判断
System.out.println(collection.contains(s2));
System.out.println(collection.isEmpty());
}
}
list子集合
- 特点:有序、有下标、元素可重复
- 方法
- 包含Collection中的方法
- add(int index,Object o) //在index位置插入对象o
- addAll(int index,Collection c) //将一个集合中的元素添加到此集合中的index位置
- get(int index) //返回集合中指定位置的元素
- subList(int fromIndex,int toIndex) //返回fromIndex和toIndex之间的集合元素
package Collectionproject;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Demo03 {
public static void main(String[] args) {
//创建list对象
List list = new ArrayList<>();
//添加元素
list.add("苹果");
list.add("华为");
list.add("小米");
System.out.println(list.size());
//删除元素
// list.remove(0);
// System.out.println(list.toString());
//遍历
//(1)for循环
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
//(2)增强for
for (Object object:list
) {
System.out.println(object);
}
//(3)Iterator迭代器
// Iterator it = list.iterator();
// while(it.hasNext()){
// System.out.println(it.next());
// }
//(4)使用列表迭代器
ListIterator lit = list.listIterator();
System.out.println("从前往后:");
while(lit.hasNext()){
System.out.println(lit.nextIndex()+":"+lit.next());
}
System.out.println("从后往前:");
while (lit.hasPrevious()){
System.out.println(lit.previousIndex()+":"+ lit.previous());
}
//4.判断
System.out.println(list.contains("苹果"));
System.out.println(list.isEmpty());
//获取
System.out.println(list.indexOf("华为"));
}
}
list实现类
-
ArrayList【重点】:
- 数组结构
- 查询快、增删慢
- JDK1.2版本,运行效率快、线程不安全
-
Vector:
- 数组结构快,查询快、增删慢
- JDK1.0,版本,运行效率慢、线程安全
-
LinkedList:
- 链表结构实现,增删快,查询慢
-
不同结构实现方式:
泛型
- java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递
- 常见形式有泛型类、泛型接口、泛型方法
- 语法:
- <T,…>T称为类型占位符,表示一种引用类型
- 好处:
- (1)提高代码的重用性
- (2)防止类型转换异常,提高代码的安全性
package MyGeneric;
/**
* 泛型类
* 语法:类名<T>
* T是类型占位符,表示一种引用类型,如果编写多个使用逗号隔开
*/
public class MyGeneric<T> {
//使用泛型T
//创建变量
T t;
//2.泛型作为方法的参数
public void show(T t){
System.out.println(t);
}
//3.泛型作为方法的返回值
public T getT(){
return t;
}
}
package MyGeneric;
public class TestGeneric {
public static void main(String[] args) {
//使用泛型类T创建对象
//注意:1.泛型只能使用引用类型
// 2.不同泛型对象不能相互赋值
MyGeneric<String> myGeneric = new MyGeneric<String>();
myGeneric.t = "Hello";
myGeneric.show("你好");
String str = myGeneric.getT();
}
}
泛型接口
package MyGeneric;
/**
1. 泛型接口
2. 语法:接口名<T>
3. 注意:不能使用泛型静态常量
4. @param <T>
*/
public interface MyInterface<T> {
String name = "张三";
T server(T t);
}
- 用之前确定类型
package MyGeneric;
public class TestMyInterface implements MyInterface<String>{
@Override
public String server(String s) {
System.out.println(s);
return s;
}
}
- 用时确定类型
package MyGeneric;
public class TestMyInterface2<T> implements MyInterface<T>{
@Override
public T server(T t) {
System.out.println(t);
return t;
}
}
泛型方法
package MyGeneric;
/**
* 泛型方法
* 语法:<T> 返回值类型
*/
public class MyGenericMethod {
//泛型方法
public <T> T show(T t){
System.out.println("泛型方法"+t);
return t;
}
}
泛型集合
- 概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致
- 特点:
- 编译时即可检查,而非运行时抛出异常
- 访问时,不必类型转换(拆箱)
- 不同泛型之间引用不能相互赋值,泛型不存在多态
package MyGeneric;
import java.util.ArrayList;
import java.util.Iterator;
public class Demo01 {
public static void main(String[] args) {
ArrayList<String> arrayList = new ArrayList();
arrayList.add("aaa");
arrayList.add("bbb");
arrayList.add("ccc");
arrayList.add("ddd");
for (String string:arrayList
) {
System.out.println(string);
}
ArrayList<student> arrayList1 = new ArrayList<student>();
student s1 = new student("郭富城",18);
student s2 = new student("张学友",20);
student s3 = new student("刘德华",19);
student s4 = new student("黎明",17);
arrayList1.add(s1);
arrayList1.add(s2);
arrayList1.add(s3);
arrayList1.add(s4);
Iterator<student> it = arrayList1.iterator();
while(it.hasNext()){
student stu = it.next();
System.out.println(stu.toString());
}
}
}
Set集合
Set子接口
- 特点:无序、无下标、元素不可重复
- 方法:全部继承自Collection中的方法
Set实现类
- HashSet【重点】:
- 基于HashCode实现元素不重复
- 当存入元素的哈希码相同时,会调用equals进行确认,如结果为true,则拒绝后者存入
- TreeSet:
- 基于排列顺序实现元素不重复
package Set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* 测试Set接口的使用
* 特点:无序、无下标、不可重复
*/
public class Demo01 {
public static void main(String[] args) {
//创建集合
Set<String> set = new HashSet<>();
//添加
set.add("苹果");
set.add("华为");
set.add("小米");
System.out.println(set.size());
System.out.println(set.toString());
//删除
set.remove("小米");
System.out.println(set.size());
//遍历【重点!!!!】
//(1)增强for
for (String string:set
) {
System.out.println(string);
}
//(2)迭代器
Iterator it = set.iterator();
while(it.hasNext()){
String str = (String) it.next();
System.out.println(str);
}
//判断
System.out.println(set.contains("华为"));
System.out.println(set.isEmpty());
}
}
- HashSet的使用
package Set;
import java.util.HashSet;
import java.util.Iterator;
/**
* HashSet的使用
* 存储结构:哈希表
*/
public class Demo02 {
public static void main(String[] args) {
//新建集合
HashSet<String> hashSet = new HashSet<>();
//添加
hashSet.add("刘德华");
hashSet.add("张学友");
hashSet.add("郭富城");
hashSet.add("黎明");
System.out.println(hashSet.size());
System.out.println(hashSet.toString());
//删除
// hashSet.remove("黎明");
//遍历
//增强for
for (String string:hashSet
) {
System.out.println(string);
}
//迭代器
Iterator<String> it = hashSet.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
//判断
System.out.println(hashSet.contains("郭富城"));
System.out.println(hashSet.isEmpty());
}
}
- TreeSet使用
- 基于排列顺序实现元素不重复
- 实现了SortedSet接口,对集合元素自动排序
- 元素对象的类型必须实现Comparable接口,指定排序规则
- 通过CompareTo方法确定是否为重复元素
package Set;
import java.util.TreeSet;
/**
* 使用TreeSet保存数据
* 存储结构:红黑树
* 要求:元素必须实现Comparable接口,compareTo()方法返回值为0,认为是重复元素
*/
public class Demo05 {
public static void main(String[] args) {
//创建集合
TreeSet<student> treeSet = new TreeSet<>();
student s1 = new student("彭于晏",18);
student s2 = new student("坤哥",20);
student s3 = new student("胡歌",19);
student s4 = new student("CTRL",21);
//添加
treeSet.add(s1);
treeSet.add(s2);
treeSet.add(s3);
treeSet.add(s4);
System.out.println(treeSet.toString());
//删除
treeSet.remove("CTRL");
//遍历
//判断
}
}
package Set;
public class student implements Comparable<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 compareTo(student o) {
int n1 = this.getName().compareTo(o.getName());
int n2 = this.age-o.getAge();
return n1==0?n2:n1;
}
}
- TreeSet集合的使用
package Set;
import java.util.Comparator;
import java.util.TreeSet;
/**
* TreeSet集合的使用
* Comparator:实现定制比较(比较器)
* Comparable:可比较的
*/
public class Demo06 {
public static void main(String[] args) {
//创建集合,并指定比较规则
TreeSet<student> treeSet = new TreeSet<>(new Comparator<Set.student>() {
@Override
public int compare(Set.student o1, Set.student o2) {
int n1 = o1.getAge()-o2.getAge();
int n2 = o1.getName().compareTo(o2.getName());
return n1==0?n2:n1;
}
});
//创建集合
student s1 = new student("彭于晏",18);
student s2 = new student("坤哥",20);
student s3 = new student("胡歌",19);
student s4 = new student("CTRL",21);
//添加
treeSet.add(s1);
treeSet.add(s2);
treeSet.add(s3);
treeSet.add(s4);
System.out.println(treeSet.toString());
}
}
Map体系集合
- Map接口特点:
- 用于存储任意键值对,无序、无下标,键不可重复,值可重复(Key-Value)
- 键:无序、无下标、不允许重复(唯一)
- 值:无序、无下标、允许重复
- 方法:
- V put(K key,V value) //将对象存入到集合中,关联键值。key重复则覆盖原值
- get(Object key)//根据键获取对应的值
- Set //返回所有的key
- Collection values() //返回包含所有值的Collection集合
- Set<Map.Entry<K,V>> //键值匹配的Set集合
- 基本操作
package Map;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Map接口的使用
* 特点:(1)存储键值对(2)键不能重复,值可以重复(3)无序
*/
public class Demo01 {
public static void main(String[] args) {
//创建Map集合
Map<String,String> map = new HashMap<>();
//1.添加元素
map.put("CN","中国");
map.put("UK","英国");
map.put("USA","美国");
System.out.println(map.toString());
//删除
map.remove("USA");
System.out.println(map.toString());
//遍历
//使用KeySet();
Set<String> keyset = map.keySet();
for (String key:keyset
) {
System.out.println(key+":"+map.get(key));
}
//使用entrySet();
Set<Map.Entry<String,String>> entries = map.entrySet();
for (Map.Entry<String,String> entry:entries
) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
//判断
System.out.println(map.containsKey("CN"));
System.out.println(map.containsValue("USA"));
}
}
Map集合实现类
-
HashMap【重点】
- JDK1.2版本,线程不安全,运行效率快;允许用null作为key或是value
package Map;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* HashMap集合使用
* 存储结构:哈希表
* 使用key的hashcode和equals作为重复
*/
public class Demo02 {
public static void main(String[] args) {
//创建集合
HashMap<Student,String> student = new HashMap<>();
//添加元素
Student s1 = new Student("张三",19);
Student s2 = new Student("李四",19);
Student s3 = new Student("王五",19);
Student s4 = new Student("赵六",19);
student.put(s1,"北京");
student.put(s2,"上海");
student.put(s3,"广州");
student.put(s4,"深圳");
System.out.println(student.toString());
//删除
//遍历
//使用keySet()
for (Student key:student.keySet()
) {
System.out.println(key.toString()+":"+student.get(key));
}
//使用entrySet()
for (Map.Entry<Student,String> entry:student.entrySet()
) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
//判断
}
}
- Hashtable:
- JDK1.0版本,线程安全,运行效率慢;不允许null作为key或是value
- Properties:
- Hashtable的子类,要求key和value都是String。通常用于配置文件的读取
- TreeMap:
- 实现了SortedMap接口(是Map的子接口),可以对key自动排序
- TreeMap的使用
package Map;
import java.security.Key;
import java.util.Map;
import java.util.TreeMap;
/**
* TreeMap的使用
* 存储结构:红黑树
*/
public class Demo03 {
public static void main(String[] args) {
//新建集合(定制比较或继承接口)
TreeMap<Student,String> treeMap = new TreeMap<>();
//添加元素
Student s1 = new Student("张三",19);
Student s2 = new Student("李四",19);
Student s3 = new Student("王五",19);
Student s4 = new Student("赵六",19);
treeMap.put(s1,"北京");
treeMap.put(s2,"上海");
treeMap.put(s3,"广州");
treeMap.put(s4,"深圳");
System.out.println(treeMap.toString());
//删除
//treeMap.remove()
//遍历
//keySet()
for (Student stu:treeMap.keySet()
) {
System.out.println(stu+":"+treeMap.get(stu));
}
//entrySet()
for (Map.Entry<Student,String> entry:treeMap.entrySet()
) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
//判断
System.out.println(treeMap.containsKey(s1));
System.out.println(treeMap.containsValue("北京"));
}
}
package Map;
public class Student implements Comparable<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 compareTo(Student o) {
int n1 = this.name.compareTo(o.getName());
int n2 = this.age-o.getAge();
return n1==0?n2:n1;
}
}
Colletions工具类
- 概念:集合工具类,定义了除了存取以外的集合常用方法
- 方法:
- reverse(List<?> list) //翻转集合中元素的顺序
- shuffle(List<?> list) //随机重置集合中元素的顺序
- sort(List list) //升序排序(元素类型必须实现Comparable接口)