【Java】集合

集合

  • 概念

对象的容器,实现了对对象常用的操作,类似数组功能。

  • 集合和数组区别

      1. 数组长度固定,集合长度不固定
      2. 数组可以存储基本类型和引用类型,集合只能存储引用类型
  • 集合所在包: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 	remove(Object o)		//在此集合中移除o对象    
int 		size()					//返回此集合中的元素个数   
Object[] 	toArray()				//将此集合转换成数组       

Collection使用


案例1

package Demo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/*
 * Collection接口的使用
 * (1)添加元素
 * (2)删除元素
 * (3)遍历元素
 * (4)判断
 */
public class Demo1 {
	public 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("榴莲");
//		collection.clear();
//		System.out.println("删除之后:"+collection.size());
		 // (3)遍历元素[重点]
			//3.1使用增强for
		System.out.println("-----------3.1使用增强for-----------");
		for(Object object : collection) {//object是每个元素
				System.out.println(object);
		}
		//3.2使用迭代(迭代器专门用来遍历集合的一种方式)
		//hasNext();有没有下一个元素
		//next();获取下一个元素
		//remove();删除当前元素
		System.out.println("-----------3.2迭代器-----------");
		Iterator it =  collection.iterator();
		while(it.hasNext()) {
			String s = (String)it.next();
			System.out.println(s);
			//在迭代过程中,不允许使用其方法操作,如:collection.remove(s);
			//若想在迭代的过程中删除元素,则可以使用下面语句
			//it.remove();
		}
		System.out.println("元素个数:" + collection.size());
		
		 // (4)判断
		System.out.println(collection.contains("西瓜"));//判断集合中是否有西瓜,返回一个布尔值
		System.out.println(collection.isEmpty());//判断集合是否为空,返回一个布尔值
	}

}

案例2

package Demo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/*Collection的使用:保存学生信息
 * 
 */
public class Demo2 {
	public static void main(String[] args) {
		//新建Collection对象
		Collection collection = new ArrayList();
		Student s1 = new Student("王俊凯",20);
		Student s2 = new Student("蔡徐坤",25);
		Student s3 = new Student("水果超甜",26);
		//1.添加数据
		collection.add(s1);
		collection.add(s2);
		collection.add(s3);
		
		System.out.println("元素个数:" + collection.size());
		System.out.println(collection.toString());
		//2.删除
		collection.remove(s1);
		System.out.println("删除之后:"+collection.size());
		//3.1、遍历(方法一:增强for循环)
		System.out.println("----增强for来实现----");
		for(Object object : collection) {
			Student s = (Student)object;
			System.out.println(s.toString());
		}
		//3.2、遍历(方法二:迭代器,它有三个方法:hasNext(),next(),remove(),迭代过程中不能使用collection的删除方法)
		System.out.println("----迭代器来实现----");
		Iterator it = collection.iterator();
		while(it.hasNext()) {
			Student s = (Student)it.next();
			System.out.println(s.toString());
		}
		//判断
		//判断是否存在
		System.out.println(collection.contains(s1));
		System.out.println(collection.contains(new 	Student("蔡徐坤",25)));//返回false
		//判断是否为空
		System.out.println(collection.isEmpty());
		
		
	}
}

List子接口


  • 特点:有序,有下标,元素可以重复。
  • 常用方法
返回值			方法名
void		add(int index,Object o) 		//在index位置插入对象o
boolean		addALL(int index,Collection c)  //将一个集合中的元素添加到此集合中的index位置
Object		get(int index)				//返回集合中指定位置的元素
List    	subList(int fromIndex,int toIndex)//返回fromIndex和toIndex之间的集合元素     

List接口使用

案例1

package Demo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/*List接口的使用
 * 特点:1.有下标	2.有序	3.可以重复
 */
public class Demo3 {
	public static void main(String[] args) {
		//1.先创建集合对象
		List list = new ArrayList<>();
		list.add("苹果");
		list.add("小米");
		list.add(0,"华为");
		
		System.out.println("元素个素:"+list.size());
		System.out.println(list.toString());
		
		//2.删除元素
		list.remove(1);
		
		System.out.println("删除之后:"+list.size());
		System.out.println(list.toString());
		
		//3.遍历
		//3.1、使用for遍历
		System.out.println("----使用for遍历----");
		for(int i = 0;i<list.size();i++) {
			System.out.println(list.get(i));
		}
		
		//3.2使用增强for
		System.out.println("----使用增强for遍历----");
		for(Object object : list) {
			System.out.println(object);
		}
		//3.3使用迭代器遍历
		Iterator it = list.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		//3.4使用列表迭代器遍历
		//和Iterator的区别,ListIterator可以指定遍历方向,添加,删除,修改元素
		System.out.println("----使用列表迭代器遍历(从前往后)----");
		ListIterator lit = list.listIterator();
		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());
		//5.获取位置
		System.out.println(list.indexOf("华为"));
	}

}

案例2

package Demo;

import java.util.ArrayList;
import java.util.List;

//List的使用
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);
		list.add(60);
		System.out.println("元素个数:"+list.size());
		System.out.println(list.toString());
		//删除操作
		list.remove((Object)20);//如果想删除数字元素,就需要转换类型,否则编译器认为这个数字是下标
		System.out.println("删除元素:"+list.size());
		System.out.println(list.toString());
		
		
		//3.补充方法subList:返回子集合,含头不含尾
		List subList = list.subList(1, 3);
		System.out.println(subList.toString());
	}

}

List实现类


  • ArrayList【重点】:

    • 数组结构实现,查询快、增删慢;
    • JDK1.2版本,运行效率快,线程不安全;
  • Vector:

    • 数组结构实现,查询快,增删慢;
    • JDK1.0版本,运行效率慢,线程安全。
  • LinkedList:

    • 链表结构实现,增删快,查询慢。

ArrayList使用

案例

package Demo;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;

/*
 * ArrayList的使用
 * 存储结构:数组,查找遍历速度快,增删慢
 */
public class Demo5 {

	public static void main(String[] args) {
		// 创建集合
		ArrayList arrayList = new ArrayList<>();
		//1.添加元素
		Student s1 = new Student("刘德华",20);
		Student s2 = new Student("郭富城",22);
		Student s3 = new Student("梁朝伟",18);
		
		arrayList.add(s1);
		arrayList.add(s2);
		arrayList.add(s3);
		
		System.out.println("元素个数:"+arrayList.size());
		System.out.println(arrayList.toString());
		//2.删除元素
		arrayList.remove(s1);
		System.out.println("删除之后:"+arrayList.size());
		//3.遍历元素【重点】
			//3.1、使用迭代器
		System.out.println("----使用迭代器----");
		Iterator it = arrayList.iterator();
		while(it.hasNext()) {
			Student s = (Student)it.next();
			System.out.println(s.toString());
		}
			//3.1、使用列表迭代器
		System.out.println("----使用列表迭代器(从前往后)----");
		ListIterator lit = arrayList.listIterator();
		while(lit.hasNext()) {
			Student s = (Student)lit.next();
			System.out.println(s.toString());
		}
		
		System.out.println("----使用列表迭代器(从后往前)----");
		while(lit.hasPrevious()) {
			Student s = (Student)lit.previous();
			System.out.println(s.toString());
		}
		
		//4.判断
		System.out.println(arrayList.contains(s1));//判断元素是否存在
		System.out.println(arrayList.isEmpty());//判断集合是否为空
		//5.查找
		System.out.println(arrayList.indexOf(s2));//查找元素下标

	}

}

ArrayList总结:

  • 默认容量大小:10
  • 没有在集合中添加任何元素,容量默认为0
  • 存放元素的数组:elementData

Vector使用


package com.qf.chapter12_2;

import java.util.Enumeration;
import java.util.Vector;

/*
 * 演示Vector集合的使用
 * 存储结构:数组
 */
public class Demo1 {

	public static void main(String[] args) {
		// 创建集合
		Vector vector = new Vector<>();
		//1.添加元素
		vector.add("草莓");
		vector.add("芒果");
		vector.add("西瓜");
		System.out.println("元素个数:"+vector.size());
		//2.删除(使用remove或clear方法,这里不做演示了)
		//3.遍历(可以使用增强for,两种迭代器,这里演示使用它特有的方法:枚举器)
		Enumeration en = vector.elements();
		while(en.hasMoreElements()) {
			String o = (String)en.nextElement();
			System.out.println(o);
		}
		//4.判断
		System.out.println(vector.contains("西瓜"));
		System.out.println(vector.isEmpty());
		
		//还有其他方法请查阅API,因为实际开发中Vector
	}

}

LinkedList使用


package com.qf.chapter12_2;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;

import Demo.Student;

/*
 * LikedList的使用
 * 存储结构:双向链表
 */
public class Demo2 {

	public static void main(String[] args) {
		// 创建集合
		LinkedList linkedList = new LinkedList<>();
		//1.添加元素
		Student s1 = new Student("刘德华",20);
		Student s2 = new Student("郭富城",22);
		Student s3 = new Student("梁朝伟",18);
		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(s1);
		System.out.println("删除之后:"+linkedList.size());
		//3.遍历
		System.out.println("----使用for遍历----");
		for(int i=0;i<linkedList.size();i++) {
			System.out.println(linkedList.get(i));
		}
		
		System.out.println("----使用增强for遍历----");
		for(Object object : linkedList) {
			Student s = (Student)object;
			System.out.println(s.toString());
		}
		
		System.out.println("----使用迭代器遍历----");
		Iterator it = linkedList.iterator();
		while(it.hasNext()) {
			Student s = (Student)it.next();
			System.out.println(s.toString());
		}
		
		System.out.println("----使用列表迭代器遍历----");
		ListIterator lit = linkedList.listIterator();
		while(lit.hasNext()) {
			Student s = (Student)lit.next();
			System.out.println(s.toString());
		}
		//判断
		System.out.println(linkedList.contains(s1));
		System.out.println(linkedList.isEmpty());
		//获取
		System.out.println(linkedList.indexOf(s1));
	}

}

泛型概述


  • Java泛型是JDK1.5中引入的一个新特性,其本质是参数化类型,把类型作为参数传递。

  • 常见形式有泛型类,泛型接口,泛型方法。

  • 语法:

    <T,…> T称为类型占位符,表示一种引用类型。

  • 好处:

    1. 提高代码的重用性
    2. 防止类型转换异常,提高代码的安全性

泛型类


泛型类

package com.qf.chapter12_2;
/*
 * 泛型类
 * 语法:类名<T,E,...>
 * T是类型占位符,表示一种引用类型,如果编写多个使用逗号隔开
 */
public class MyGeneric<T> {
	//使用泛型T
	//1.创建变量
	T t;
	//2.泛型作为方法的参数
	public void show(T t) {
		System.out.println(t);
	}
	//3.泛型作为方法的返回值
	public T getT() {
		return t;
	}
}

使用类

package com.qf.chapter12_2;

public class TestGeneric {
	public static void main(String[] args) {
		//使用泛型类创建对象
		MyGeneric<String> myGeneric = new MyGeneric<String>();
		myGeneric.t = "hello";
		myGeneric.show("大家好");
		String string = myGeneric.getT();
		
		
		MyGeneric<Integer> myGeneric2 = new MyGeneric<Integer>();
		myGeneric2.t=100;
		myGeneric2.show(200);
		Integer integer = myGeneric2.getT();
		//注意:1.泛型只能使用引用类型
//				2.不同泛型类型对象不能直接相互赋值
		
	}
	
}

泛型接口


  • 泛型接口

package com.qf.chapter12_2;
/*
 * 泛型接口
 * 语法:接口名<T>
 * 注意:不能用泛型创建泛型常量
 */
public interface MyInterface <T>{
	//静态常量
	String name = "张三";
	//方法
	T server(T t);//参数为T,返回值也为T
	

}

  • 实现类

方式一:指定T的类型

package com.qf.chapter12_2;

public class MyInterfaceImpl implements MyInterface<String>{

	@Override
	public String server(String t) {
		System.out.println(t);
		return null;
	}

}

方式2:T类型未确定

package com.qf.chapter12_2;

public class MyInterfaceImpl2<T> implements MyInterface<T> {

	@Override
	public T server(T t) {
		System.out.println(t);
		return t;
	}

}

  • 测试类

package com.qf.chapter12_2;

public class TestGeneric {
	public static void main(String[] args) {
        //测试方式一
		MyInterfaceImpl impl = new MyInterfaceImpl();
		impl.server("随便放个字符串");
        //测试方式二
        MyInterfaceImpl2<Integer> impl2 = new MyInterfaceImpl2<>();
        impl2.server(10000);
        
	}
	
}

泛型方法


  • 创建泛型方法
package com.qf.chapter12_2;
/*
 * 泛型方法
 * 语法:<T>返回值类型
 */
public class MyGenericMethod {
	//泛型方法
	public <T> void show(T t) {//这里返回值也可以换成T
		System.out.println("泛型方法"+t);
		
	}
}

  • 测试类
package com.qf.chapter12_2;

public class TestGeneric {
	public static void main(String[] args) {
		
        //泛型方法测试
        MyGenericMethod myGenericMethod = new MyGenericMethod();
        myGenericMethod.show("这是一个字符串");
        myGenericMethod.show(200);
        myGenericMethod.show(3.14);//泛型的类型是由传入的数据决定的
		
	}
	
}

泛型集合


  • 概念:参数化类型,类型安全的集合,强制集合元素的类型必须一致。

  • 特点:

    • 编译时即可检查,而非运行是抛出异常。
    • 访问是,不必类型转换(拆箱)。
    • 不同泛型之间引用不能相互扶助,泛型不存在多态。

泛型集合使用

在这里插入图片描述

Set(子接口)集合


  • 特点:无序、无下标,元素不可重复

  • 方法:都是继承Collection类里的方法


Set接口的使用
package com.qf.chapter12_3;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

//测试Set接口的使用
//特点:无序,无下标,不能重复
public class Demo1 {

	public static void main(String[] args) {
		// 创建集合
		Set<String> set = new HashSet<>();
		//1.添加数据
		set.add("小米");
		set.add("苹果");
		set.add("华为");
//		set.add("华为");  虽然这句没报错。但打印时只有一个"华为"
		System.out.println("数据个数:"+set.size());
		System.out.println("删除前:"+set.toString());
		//2.删除数据
		set.remove("小米");
		System.out.println("删除后:"+set.toString());
		//3.遍历(两种方式)【重点】
		System.out.println("----使用增强for遍历----");
		for(String string : set) {
			System.out.println(string);
		}
		
		System.out.println("----使用迭代器遍历----");
		Iterator<String> it = set.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		//判断
		System.out.println(set.contains("华为"));
		System.out.println(set.isEmpty());
		
	}

}

通常,一般情况下建议使用Set下的实现类

Set实现类


  • HashSet【重点】:

    • 基于HashCode计算元素存放位置
    • 当存入元素的哈希嘛相同时,会调用equals进行确认,如果结果为true,则拒绝后者存入。
  • TreeSet:
    • 基于排列顺序实现元素不重复。
    • 实现了SortedSet接口,对集合元素自动排序。
    • 元素对象的类型必须实现Comparable接口,指定排序规则。
    • 通过CompareTo方法确定是否为重复元素。

HashSet使用


案例1

package com.qf.chapter12_3;

import java.util.HashSet;
import java.util.Iterator;

//HashSet的使用
public class Demo2 {

	public static void main(String[] args) {
		// 创建集合
		HashSet<String> hashSet = new HashSet<String>();
		//1、添加元素
		hashSet.add("王源");
		hashSet.add("王俊凯");
		hashSet.add("易烊千玺");
		hashSet.add("蔡徐坤");
		System.out.println("元素的个数:"+hashSet.size());
		System.out.println("删除前:"+hashSet.add(null));
		//2、删除数据
		hashSet.remove("蔡徐坤");
		System.out.println("删除后:"+hashSet.add(null));
		//3、遍历
		System.out.println("使用for遍历");
		for(String string : hashSet) {
			System.out.println(string);
		}
		
		System.out.println("使用迭代器遍历");
		Iterator<String> it = hashSet.iterator();
		while(it.hasNext()) {
			System.out.println(it.next());
		}
		//4、判断
		System.out.println(hashSet.contains("彭于晏"));
		System.out.println(hashSet.isEmpty());
	}

}

案例2

人类

package com.qf.chapter12_3;

public class Person {
	private String name;
	private int age;
	//添加构造方法
	public Person() {
		super();
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	//get/set
	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 "Person [name=" + name + ", age=" + age + "]";
	}
	
}

测试类

package com.qf.chapter12_3;

import java.util.HashSet;

/*
 * HashSet的使用
 * 存储结构:哈希表(素组+链表+红1黑树)
 * 存储过程(重复依据)
 * 1、根据hashcode计算保存的位置。如果此位置为空,则直接保存,如果不为空执行第二步
 * 2、再执行equals方法,如果equals方法为true,则认为是重复,否则形成链表
 */
public class Demo3 {
	public static void main(String[] args) {
		//创建集合
		HashSet<Person> persons = new HashSet();
		//1、添加数据
		Person p1 = new Person("佩奇",8);
		Person p2 = new Person("乔治",3);
		Person p3 = new Person("汪汪队",0);
		
		persons.add(p1);
		persons.add(p2);
		persons.add(p3);
		persons.add(new Person("佩奇",8));//通过这种方法可以添加相同数据,但内存地址不同
		
		
		System.out.println("元素个数:"+persons.size());
		System.out.println("删除前:"+persons.toString());
		
		
	}
}

TreeSet使用


案例1

package com.qf.chapter12_3;

import java.util.TreeSet;

/*存储结构:红黑树
 * TreeSet的使用
 */
public class Dmeo4 {

	public static void main(String[] args) {
		// 创建集合
		TreeSet<String> treeSet = new TreeSet<>();
		//添加元素
		treeSet.add("xyz");
		treeSet.add("abc");
		treeSet.add("hello");
		
		System.out.println("元素个数:"+treeSet.size());
		System.out.println(treeSet.toString());
		//删除【和HashSet例子一样】
		//遍历【和HashSet例子一样】
		//判断【和HashSet例子一样】
				
;
	}

}

案例2

测试类

package com.qf.chapter12_3;

import java.util.TreeSet;

/*
 * TreeSet的使用
 * 存储结构:红黑树
 * 要求:元素必须实现Comparable接口,compareTo()方法返回值为0,认为是重复元素
 */
public class Demo5 {

	public static void main(String[] args) {
		// 创建紧耦合
		TreeSet<Person> person = new TreeSet<>();
		//添加元素
		Person p1 = new Person("王源",20);
		Person p2 = new Person("王俊凯",22);
		Person p3 = new Person("易烊千玺",23);
		
		person.add(p3);
		person.add(p2);
		person.add(p1);
		System.out.println("元素个数:"+person.size());
		System.out.println(person.toString());
	}

}

Person类

package com.qf.chapter12_3;

public class Person implements Comparable<Person> {
	private String name;
	private int age;
	//添加构造方法
	public Person() {
		super();
	}
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	//get/set
	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 "Person [name=" + name + ", age=" + age + "]";
	}
	//重写比较方法(自定义比较规则)
	@Override
	public int compareTo(Person o) {
		//先按姓名比。然后再按年龄比。
		int n1 = this.getName().compareTo(o.getName());
		int n2 = this.age-o.getAge();
		//compareTo()方法返回值为0,认为是重复元素
		return  n1 == 0?n2:n1;
	}
	
}

Comparator接口


package com.qf.chapter12_3;

import java.util.TreeSet;

/*
 * TreeSet的使用
 * 存储结构:红黑树
 * 要求:元素必须实现Comparable接口,compareTo()方法返回值为0,认为是重复元素
 */
public class Demo5 {

	public static void main(String[] args) {
		// 创建紧耦合
		TreeSet<Person> person = new TreeSet<>();
		//添加元素
		Person p1 = new Person("王源",20);
		Person p2 = new Person("王俊凯",22);
		Person p3 = new Person("易烊千玺",23);
		
		person.add(p3);
		person.add(p2);
		person.add(p1);
		System.out.println("元素个数:"+person.size());
		System.out.println(person.toString());
	}

}

TreeSet案例

package com.qf.chapter12_3;

import java.util.Comparator;
import java.util.TreeSet;

/*
 * 要求:使用TreeSet集合实现字符串按照长度排序
 * helloworld zhang lisi wangwu beijinng xian nanjing
 * 
 */
public class Demo7 {

	public static void main(String[] args) {
		//创建集合并指定比较规则
		//以字符串长度进行比较
		TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {

			@Override
			public int compare(String o1, String o2) {
				int n1 = o1.length()-o2.length();
				int n2 = o1.compareTo(o2);
				return n1==0?n2:n1;
			}
			
		});
		//添加数据
		treeSet.add("helloworld");
		treeSet.add("zhang");
		treeSet.add("lisi");
		treeSet.add("wangwu");
		treeSet.add("beijinng");
		treeSet.add("xian");
		treeSet.add("nanjing");
		treeSet.add("cat");
		
		System.out.println("元素个数:"+treeSet.size());
		System.out.println("元素:"+treeSet.toString());

	}

}

Map集合


Map集合体系

在这里插入图片描述

Map父接口
  • 特点:存储一对数据(Key-Value),无序、无下标、键不可重复,值可以重复。
  • 常用方法:
    1. V put(K key,V value) //将对象存入到集合中,关键键值。key重复则覆盖原值。
    2. Object get(Object key) //根据键获取对应的值。
    3. Set //返回所有key。
    4. Collection values() //返回包含所有值的Collection集合。
    5. Set<Map.Entry<K,V>> //键值匹配的set集合

Map接口的使用

Map集合


Map集合体系

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-PX2FSV2j-1682517958246)(G:\学习\笔记\1.JAVA\JAVA集合框架\图像\Map集合体系.jpg)]

Map父接口
  • 特点:存储一对数据(Key-Value),无序、无下标、键不可重复,值可以重复。
  • 常用方法:
    1. V put(K key,V value) //将对象存入到集合中,关键键值。key重复则覆盖原值。
    2. Object get(Object key) //根据键获取对应的值。
    3. Set //返回所有key。
    4. Collection values() //返回包含所有值的Collection集合。
    5. Set<Map.Entry<K,V>> //键值匹配的set集合

Map集合的实现类

  • HashMap【重点】

    • JDK1.2版本,线程不安全,运行效率快;允许用null作为key或是value。
  • Hashtable(很少用到):

    • JDK1.0版本,线程安全,运行效率慢;不允许null作为key或value。
  • Properties(讲到流时介绍):

    • Hashtable的子类,要求key和value都是String。通常用于配置文件的读取。
  • TreeMap:

    • 实现lSortedMap接口(时Map的子接口),可以对key自动排序。

HashMap使用


Student类

package com.qf.chapter12_4;

public class Student {
	private String name;
	private int stuNo;
	//构造方法
	public Student() {
		
	}
	public Student(String name, int stuNo) {
		super();
		this.name = name;
		this.stuNo = stuNo;
	}
	//get/set
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getStuNo() {
		return stuNo;
	}
	public void setStuNo(int stuNo) {
		this.stuNo = stuNo;
	}
	//toString
	@Override
	public String toString() {
		return "Student [name=" + name + ", stuNo=" + stuNo + "]";
	}
	//生成hashcode和equals方法
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + stuNo;
		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 (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (stuNo != other.stuNo)
			return false;
		return true;
	}
	
	//
	
	
	

}

测试类

package com.qf.chapter12_4;

import java.util.HashMap;

/*
 * HashMap集合的使用
 * 存储结构:哈希表(数组+链表+红黑树)
 */
public class Demo2 {

	public static void main(String[] args) {
		// 创建集合
		HashMap<Student,String> students = new HashMap<Student,String>();
		//添加元素
		Student s1 = new Student("王源",22000371);
		Student s2 = new Student("王俊凯",22000372);
		Student s3 = new Student("易烊千玺",22000373);
		students.put(s1,"上海");
		students.put(s2,"北京");
		students.put(s3,"杭州");
		//如果想名字和学号一样的学生不能再次加入进来,则需要在student类中重写hashcode和equals方法
		students.put(new Student("易烊千玺",22000373),"杭州");
		
		System.out.println("元素数量:"+students.size());
		System.out.println(students.toString());
		
	}

}

TreeMap的使用


package com.qf.chapter12_4;

import java.util.Comparator;
import java.util.TreeMap;

/*
 * TreeMap的使用
 * 存储结构:红黑树
 */
public class Dmeo3 {

	public static void main(String[] args) {
		//创建集合(定制比较)
		TreeMap<Student,String> treeMap = new TreeMap<Student,String>(new Comparator<Student>() {

			@Override
			public int compare(Student o1, Student o2) {
				//写比较规则
				return 0;
			}
		});
		//1、添加元素
		Student s1 = new Student("王源",22000371);
		Student s2 = new Student("王俊凯",22000372);
		Student s3 = new Student("易烊千玺",22000373);
		treeMap.put(s1,"上海");
		treeMap.put(s2,"北京");
		treeMap.put(s3,"杭州");
		//因为涉及到比较,所以要在Student中实现Comparable接口的compareTo方法
		//如果使用定制比较,就不需要实现接口了
		System.out.println("元素数量:"+treeMap.size());
		System.out.println(treeMap.toString());
		//2、删除
		treeMap.remove(s3);
		//3、遍历(1.使用keyset方法。2.使用entryset方法)
		//4、判断
		System.out.println(treeMap.containsKey(s3));
		System.out.println(treeMap.containsValue("杭州"));
		
		

	}

}

Collections工具类


  • 概念:集合工具类,定义了除了存取以外的集合常用方法
  • 方法:
    1. public static void reverse(List<?> list) //反转集合中元素的顺序
    2. public static void shuffle(List<?> list) //随机重置集合元素的顺序
    3. public static void sort(List list) //升序排序(元素类型必须实现Comparable接口)

Collections工具类的使用

package com.qf.chapter12_4;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/*
 * 演示Collections工具类的使用
 */
public class Demo4 {

	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		list.add(20);
		list.add(5);
		list.add(12);
		list.add(30);
		list.add(6);
		//sort排序
		System.out.println("排序之前:"+list.toString());
		Collections.sort(list);
		System.out.println("排序之后:"+list.toString());
		
		//binarySearch 二分查找
		int i = Collections.binarySearch(list,12);//找list集合的12
		System.out.println(i);//输出下标,没有的元素则输出负数
		
		//copy复制
		List<Integer> dest = new ArrayList<>();
		//复制需要两个集合大小一样
		for(int k=0;k<list.size();k++) {
			dest.add(0);
		}
		Collections.copy(dest, list);//把list集合复制给dest集合
		System.out.println(dest.toString());
		
		//reverse反转元素顺序
		Collections.reverse(list);
		System.out.println("反转之后:"+list);
		
		//shuffle打乱元素顺序
		Collections.shuffle(list);
		System.out.println("打乱顺序之后:"+list);
		
		
		
		//list转化成数组
		System.out.println("----list转化成数组----");
		Integer[] arr = list.toArray(new Integer[0]);//数组长度为0,如果给的数据过长,多余长度为null
		System.out.println(arr.length);
		System.out.println(Arrays.toString(arr));
		
		
		//数组转换成集合
		System.out.println("----数组转换成集合----");
		String[] name = {"王俊凯","易烊千玺","王源"};
		List<String> list2 = Arrays.asList(name);
		//注意:转换后的集合是一个受限集合,是不能删除和添加元素的
		System.out.println(list2);
		//再来一个,基本类型转化成集合时,需要修改为包装类型
		Integer[] nums = {100,200,300,00,500};
		List<Integer> list3 = Arrays.asList(nums);
		System.out.println(list3);
		

	}

}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值