一、集合
1、集合的概念
集合:对象的容器,定义了对多个对象进行操作的常用方法,可实现类似数组的功能。
集合和数组的区别:
2、Collection接口
(1)Collection父接口
特点:代表一组任意类型的对象。
纠正:上图判断是否相等是equals()
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* Collection接口使用
* 1、添加元素
* 2、删除元素
* 3、遍历元素
* 4、判断(元素是否存在 是否为空)
* @author ymx
*/
public class demo_collection {
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);//调用toString方法
//2、删除元素
// collection.remove("香蕉");
// System.out.println("删除之后:"+collection.size());
// System.out.println(collection);
// //5、清空
// collection.clear();
// System.out.println("清空之后:"+collection.size());
// System.out.println(collection);
//3、遍历元素*
//方式一 增强的for循环
System.out.println("-------------1、使用增强的for循环遍历------------");
for (Object object:collection){
System.out.println(object);
}
//方式二 迭代器: 专门用来遍历集合的一种方式
/*
迭代器 3个方法
hasNext() 是否有下一个元素 还有元素吗?
next()获取下一个元素
remove()移除元素
在迭代器遍历中不能够使用Collection的修改删除方法 并发修改异常(不能够使用Collection的其他方法改变集合元素)
Exception in thread "main" java.util.ConcurrentModificationException
*/
System.out.println("-------------2、使用迭代器循环遍历------------");
Iterator it= collection.iterator();
while(it.hasNext()){
String s=(String)it.next();
System.out.println(s);
//collection.remove(s);不能使用Collection的删除方法
// it.remove();//但可以使用迭代器自己的删除方法
}
System.out.println("元素个数:"+collection.size());
//4、判断
//4.1 判断某元素是否存在
System.out.println(collection.contains("西瓜"));
//4.2判断集合是否为空
System.out.println(collection.isEmpty());
}
}
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
/**
* Collection的使用
* 保存学生信息 需新建学生类
*/
public class Demo1_collection {
public static void main(String[] args){
Collection collection=new ArrayList();
//1添加学生数据
Student s1=new Student("HELEN",20);
Student s2=new Student("JANE",25);
Student s3=new Student("MACTICAL",21);
//加的是地址 删除的是指向的指针
collection.add(s1);
collection.add(s2);
collection.add(s3);
collection.add(s3);//List可以元素重复
System.out.println("元素个数:"+collection.size());
System.out.println(collection.toString());
//2、删除
collection.remove(s3);//只删掉了第一个遇到的s3
System.out.println("删除之后的元素个数:"+collection.size());
System.out.println(collection.toString());
collection.remove(s3);//删掉了原第二个s3
System.out.println("删除之后的元素个数:"+collection.size());
System.out.println(collection.toString());
//3、清空
collection.clear();
System.out.println("清空之后的元素个数:"+collection.size());
collection.add(s1);
collection.add(s2);
collection.add(s3);
//4、遍历
System.out.println("-------------1、使用增强的for循环遍历------------");
for (Object object:collection){
Student s=(Student)object;
System.out.println(s.toString());
}
System.out.println("-------------2、使用迭代器循环遍历------------");
Iterator it=collection.iterator();
while(it.hasNext()){
Student ss=(Student)it.next();
System.out.println(ss.toString());
}
//5、判断
System.out.println(collection.contains(s1));
System.out.println(collection.isEmpty());
}
}
3、List接口与实现类
(1)List子接口: 特点:有序、有下标、元素可以重复。
/**
* List子接口的使用
* 特点:有序 有下标可重复
* @author ymx
*/
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class Demo1_List {
public static void main(String[] args){
//先创建集合对象
List list=new ArrayList();
//1、添加元素
list.add("苹果手机");
list.add("小米手机");
list.add(0,"华为手机");
System.out.println("元素个数:"+list.size());
System.out.println(list.toString());
System.out.println(list);
//2、删除元素
// list.remove("苹果手机");
// System.out.println("删除之后的元素个数:"+list.size());
// System.out.println(list.toString());
// list.remove(0);
// System.out.println("删除之后的元素个数:"+list.size());
// System.out.println(list.toString());
// list.clear();
// System.out.println("清空之后的元素个数:"+list.size());
//3、遍历元素:增强for 迭代器 for
System.out.println("-----for----------");
for(int i=0;i<list.size();i++){
System.out.println(list.get(i));
}
System.out.println("-----增强for----------");
for(Object object:list){
System.out.println(object);
}
System.out.println("-----迭代器iterator----------");
Iterator it=list.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
/*
列表迭代器listIterator:允许按任意方向遍历列表、迭代期间修改列表,并获得迭代器在列表中的当前位置
与迭代器iterator区别:
列表迭代器listIterator 可以向前或向后遍历 可添加删除和修改
*/
ListIterator lit=list.listIterator();
System.out.println("-----列表迭代器listIterator从前往后----------");
while(lit.hasNext()){
System.out.println(lit.nextIndex()+":"+lit.next());
// System.out.println(lit.next()+","+lit.nextIndex());
}
System.out.println("-----列表迭代器listIterator从后往前----------");
//此时指针已经移到最后了 所以才能这么用 否则要先将指针挪到最后 要不遍历不了
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("苹果手机"));
}
}
import java.util.ArrayList;
import java.util.List;
/**
* 保存数字数据
*/
public class Demo2_List {
public static void main(String[] args){
List list=new ArrayList();
//集合不能保存基本数据类型 这里有一个自动装箱的操作 包装类Integer
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(20);//报错 他这里默认就调用 使用下标的删除 会报数组越界的错误
//Exception in thread "main" java.lang.IndexOutOfBoundsException:
//下标或强制类型转换可以
// list.remove(0);
//list.remove((Object)20);
list.remove(new Integer(20));
System.out.println("删除之后元素个数:"+list.size());
System.out.println(list.toString());
//subList方法 左包含右不包含 含头不含尾
List subList=list.subList(1,3);
System.out.println(subList);
System.out.println(list);
}
}
(2)List实现类:
①ArrayList:数组列表集合,内部采用数组方式存储。数组结构实现、查询快、增删慢;运行速率快、线程不安全。
②Vertor:数组结构实现、查询快、增删慢;运行效率慢、线程安全。
③LinkedList:链表结构实现、增删快、查询慢;运行效率、线程不安全。
ArrayList源码分析:
默认容量大小:DEFAULT_CAPACITY = 10
注:如果没有向集合中添加任何元素时容量是0;添加一个元素之后容量就是10,10个之后会扩容,每次扩容大小为原来的1.5倍。
存放元素的数组:elementData
实际元素个数:size
添加元素:add
public boolean add(E e) {
ensureCapacityInternal(size + 1); // Increments modCount!!
elementData[size++] = e;
return true;
}
private static int calculateCapacity(Object[] elementData, int minCapacity) {
if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
return Math.max(DEFAULT_CAPACITY, minCapacity);
}
return minCapacity;
}
private void ensureCapacityInternal(int minCapacity) {
ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
}
private void ensureExplicitCapacity(int minCapacity) {
modCount++;
// overflow-conscious code
if (minCapacity - elementData.length > 0)
grow(minCapacity);
}
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
例子:添加、删除、查询、遍历、判断
import java.util.ArrayList;
import java.util.Iterator;
import java.util.ListIterator;
/**
* ArrayList的使用
* 存储结构:数组 查询遍历快 增删慢
*/
public class Demo1_ArrayList {
public static void main(String[] args){
ArrayList arrayList=new ArrayList();
Student s1=new Student("肖战",29);
Student s2=new Student("王一博",23);
Student s3=new Student("陈情令",2);
arrayList.add(s1);
arrayList.add(s2);
arrayList.add(s3);
System.out.println("元素个数:"+arrayList.size());
System.out.println(arrayList.toString());
// arrayList.remove(s1);
// System.out.println("元素个数:"+arrayList.size());
arrayList.remove(new Student("王一博",23));
//这样删不掉 内部调用Object的equals方法判断的是false ,equals(this==obj)使用地址作比较的 需要重写equals方法
System.out.println("删除后的元素个数:"+arrayList.size());
System.out.println(arrayList.toString());
System.out.println("-----迭代器iterator----------");
Iterator it=arrayList.iterator();
while(it.hasNext()){
Student s=(Student)it.next();
System.out.println(s.toString());
}
System.out.println("-----列表迭代器listIterator从前往后----------");
ListIterator lit=arrayList.listIterator();
while(lit.hasNext()){
Student s=(Student)lit.next();
System.out.println(s.toString());
}
System.out.println(arrayList.contains(new Student("肖战",29)));
System.out.println(arrayList.isEmpty());
System.out.println(arrayList.indexOf(s1));
}
}
Vector: Vector类实现了可扩展的对象数组。
import java.util.Enumeration;
import java.util.Vector;
/**
* Vector集合
* 存储结构:数组
*/
public class Demo_vector {
public static void main(String[] args){
Vector vector=new Vector();
vector.add("草莓");
vector.add("苹果");
vector.add("西瓜");
System.out.println(vector.size());
//使用枚举器
Enumeration en =vector.elements();
while(en.hasMoreElements()){
String o=(String)en.nextElement();
System.out.println(o.toString());
}
}
}
LinkedList源码分析:
int size:集合的大小
Node first:链表的头节点
Node last: 链表的尾节点
void linkLast(E e) {
final Node<E> l = last;
final Node<E> newNode = new Node<>(l, e, null);
last = newNode;
if (l == null)
first = newNode;
else
l.next = newNode;
size++;
modCount++;
}
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
Node(Node<E> prev, E element, Node<E> next) {
this.item = element;
this.next = next;
this.prev = prev;
}
}
例子:添加、删除、查询、遍历、判断
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
/**
* LinkedList的使用
* 存储结构:双向链表
*/
public class Demo1_LinkedList {
public static void main(String[] args){
LinkedList linkedList=new LinkedList();
Student s1=new Student("肖战",29);
Student s2=new Student("王一博",23);
Student s3=new Student("肖战",22);
linkedList.add(s1);
linkedList.add(s2);
linkedList.add(s3);
System.out.println(linkedList.size());
System.out.println(linkedList.toString());
linkedList.remove(s3);
System.out.println(linkedList.toString());
// linkedList.clear();
for(int i=0;i<linkedList.size();i++){
System.out.println(linkedList.get(i));
}
for(Object object:linkedList){
Student s=(Student)object;
System.out.println(s);
}
Iterator it=linkedList.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
ListIterator lit=linkedList.listIterator();
while(lit.hasNext()){
System.out.println(lit.next());
}
System.out.println(linkedList.contains(s1));
System.out.println(linkedList.isEmpty());
System.out.println(linkedList.indexOf(s1));
}
}
ArrayList和LinkedList的区别:
4、泛型和工具类
(1)本质: 参数化类型,把类型作为参数传递;JDK1.5引入
(2)常见形式: 泛型类、泛型接口、泛型方法。
(3)语法: <T,…> T称为类型占位符,表示一种引用类型。
(4)好处: 提高代码的重用性;防止类型转换异常,提高代码的安全性。
泛型类、泛型接口、泛型方法
/**
* 泛型类
* 语法 在类名的后边加上<T>
* T 类型占位符 表示一种引用类型 如果编写多个使用逗号隔开
*/
public class Demo1_generic<T> {
//使用泛型T
//1、创建变量
T t;
//2、泛型 作为方法的参数
public void show(T t){
//不能new一个对象 不能实例化
System.out.println(t);
}
//3、泛型 作为方法的返回值
public T getT(){
return t;
}
}
/**
* 泛型接口
* 语法 接口名<T>
* 不能使用泛型创建静态常量
*/
public interface My_Interface<T> {
//包含抽象方法和静态常量
String name="HELEN";
T server(T t);
}
public class MyInterfaceImpl implements My_Interface<String>{
public String server(String t){
System.out.println(t);
return null;
}
}
public class MyInterfaceImpl2<T> implements My_Interface<T> {
@Override
public T server(T t) {
System.out.println(t);
return null;
}
}
/**
* 泛型方法
* 语法:放在方法返回值的前边
* <T>返回值类型
*/
public class MyGenericMethod {
//泛型方法
public <T> T show(T t){
System.out.println("泛型方法"+t);
return t;
}
}
public class TestGeneric {
public static void main(String[] args){
//使用泛型类
//注:泛型只能使用引用对象,不同泛型类型对象之间不能相互赋值
Demo1_generic<String> myGeneric=new Demo1_generic<>();
myGeneric.t="hello";
myGeneric.show("hello world");
String s=myGeneric.getT();
System.out.println(s);
Demo1_generic<Integer> myGeneric2=new Demo1_generic<>();
myGeneric2.t=1000;
myGeneric2.show(2000);
System.out.println(myGeneric2.getT());
//Demo1_generic<String> myGeneric4=myGeneric2;不同泛型类型对象之间不能相互赋值 会报错
//Demo1_generic<String> myGeneric4=myGeneric; 同泛型类型对象之间能相互赋值
MyInterfaceImpl impl=new MyInterfaceImpl();
impl.server("helen");
MyInterfaceImpl2<Integer> impl2=new MyInterfaceImpl2<>();
impl2.server(1234);
//泛型方法
MyGenericMethod myGenericMethod=new MyGenericMethod();
myGenericMethod.show("hello world generic");
myGenericMethod.show(200);
}
}
(5)泛型集合
概念:参数化类型、类型安全的集合,强制集合元素的类型必须一致。
特点:编译时即可检查,而非运行时抛出异常;访问时,不必类型转换(拆箱);不同泛型之间引用不能相互赋值,泛型不存在多态。
import java.util.ArrayList;
import java.util.Iterator;
public class Demo3 {
public static void main(String[] args){
ArrayList<String> arrayList=new ArrayList<String>();
arrayList.add("xxx");
arrayList.add("aaa");
// arrayList.add(123);
// arrayList.add(234);
// for(Object object:arrayList){
// //Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String
// String str=(String)object;
// System.out.println(str);
// }
for(String string:arrayList){
System.out.println(string);
}
ArrayList<Student> arrayList2=new ArrayList<Student>();
Student s1=new Student("肖战",29);
Student s2=new Student("肖战",19);
arrayList2.add(s1);
arrayList2.add(s2);
Iterator<Student> it=arrayList2.iterator();
while(it.hasNext()){
Student a=it.next();
System.out.println(a);
}
}
}
5、Set接口与实现类
(1)Set接口: 特点:无序、无下标、元素不可以重复。
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* 测试Set接口的使用
* 无序(添加和遍历顺序不一致、无下标 元素不能重复)
*/
public class Demo_set {
public static void main(String[] args){
Set<String> set=new HashSet<>();
//1 添加数据
set.add("apple phone");
set.add("HUAWEI ");
set.add("xiaomi");
System.out.println(set.size());
System.out.println(set.toString());
//2、删除数据
// set.remove("xiaomi");
// System.out.println(set.toString());
// set.clear();
// System.out.println(set.size());
//3、遍历
//增强for 没有下标 普通循环不行
System.out.println("-------增强for--------------");
for(String string:set){
System.out.println(string);
}
System.out.println("-------迭代器iteritor--------------");
Iterator<String> iterator=set.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
//4、查找判断
System.out.println(set.contains("huawei"));
System.out.println(set.isEmpty());
}
}
(2)Set实现类:
import javax.print.attribute.HashAttributeSet;
import java.util.HashSet;
import java.util.Iterator;
/**
* HashSet 集合的使用
* 存储结构:哈希表(数组+链表+红黑树)
*/
public class Demo_HashSet {
public static void main(String[] args){
HashSet<String> hashSet=new HashSet<>();
hashSet.add("xiaozhan");
hashSet.add("xiaozan");
hashSet.add("me");
System.out.println(hashSet.size());
System.out.println(hashSet.toString());
hashSet.remove("me");
System.out.println(hashSet.toString());
System.out.println("-------增强for--------------");
for(String string:hashSet){
System.out.println(string);
}
System.out.println("-------迭代器iteritor--------------");
Iterator<String> iterator=hashSet.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println(hashSet.contains("me"));
System.out.println(hashSet.isEmpty());
}
}
public class Person {
private String name;
private int age;
public Person(){
}
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 "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int hashCode() {
int n1=this.name.hashCode();
int n2=this.age;
return n1+n2;
}
@Override
public boolean equals(Object obj) {
if(this==obj){
return true;
}
if(this==null){
return false;
}
if(obj instanceof Person){
Person p =(Person)obj;
if(this.name.equals(p.getName())&&this.age==p.getAge()){
return true;
}
}
return false;
}
}
import java.util.HashSet;
import java.util.Iterator;
/**
*使用HashSet
* 存储结构 哈希表
* 存储过程:
* (1)根据hashcode计算保存的位置,如果此位置为空,则直接保存,如果不为空指定第二步
* (2)在执行equals方法,如果equals方法结果为true 则认为重复,否则形成链表
*/
public class Demo1_HashSet {
public static void main(String[] args) {
HashSet<Person> person=new HashSet<>();
Person p1=new Person("zhangsna",22);
Person p2=new Person("zhaa",22);
Person p3=new Person("zz",22);
person.add(p1);
person.add(p2);
person.add(p3);
System.out.println(person.size());
System.out.println(person.toString());
person.add(new Person("zz",22));
//重写两个方法 hashCode equals 确保名字年龄一样的不会被加进来
//如果不重写的话 它们是不同的对象 就会被填进来
System.out.println(person.toString());
person.remove(p3);
System.out.println(person.toString());
person.remove(new Person("zhaa",22));//重写那两个方法后可以删掉
System.out.println(person.toString());
person.add(p2);
person.add(p3);
System.out.println("-------增强for--------------");
for(Person person1:person){
System.out.println(person1);
}
System.out.println("-------迭代器iteritor--------------");
Iterator<Person> iterator=person.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println(person.contains(p1));
System.out.println(person.contains(new Person("zhaa",22)));
System.out.println(person.isEmpty());
}
}
import java.util.Iterator;
import java.util.TreeSet;
/**
* TreeSet
* 存储结构 红黑树
* 要求 元素必须实现Comparable接口,compareTo()方法返回值为0,认为是重复元素
*/
public class Demo1_TreeSet {
public static void main(String[] args) {
TreeSet<Person> persons=new TreeSet<>();
//Exception in thread "main" java.lang.ClassCastException: Person cannot be cast to java.lang.Comparable
Person p1=new Person("a肖战",29);
Person p2=new Person("a肖",29);
Person p3=new Person("b战",29);
Person p4=new Person("a肖战",9);
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);
System.out.println(persons.toString());
persons.remove(p1);
System.out.println(persons.toString());
persons.remove(p2);
System.out.println(persons.toString());
System.out.println("-----for----");
for(Person s:persons){
System.out.println(s);
}
System.out.println("-----iterator----");
Iterator<Person> iterator=persons.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());
}
System.out.println(persons.contains(p3));
System.out.println(persons.contains(new Person("b战",29);));
System.out.println(persons.isEmpty());
}
}
public class Person implements Comparable<Person>{
private String name;
private int age;
public Person(){
}
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 "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int hashCode() {
int n1=this.name.hashCode();
int n2=this.age;
return n1+n2;
}
@Override
public boolean equals(Object obj) {
if(this==obj){
return true;
}
if(this==null){
return false;
}
if(obj instanceof Person){
Person p =(Person)obj;
if(this.name.equals(p.getName())&&this.age==p.getAge()){
return true;
}
}
return false;
}
//先按姓名比较 再按年龄比较
@Override
public int compareTo(Person o) {
int n1=this.getName().compareTo(o.getName());
int n2=this.age-o.getAge();
return n1==0?n2:n1;
}
}
import java.util.Comparator;
import java.util.TreeSet;
/**
* TreeSet的使用
* Comparator: 实现定制比较、比较器
* Comparable:可比较的
*/
public class Demo2_TreeSet {
public static void main(String[] args) {//匿名内部类
TreeSet<Person> persons=new TreeSet<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int n1=o1.getAge()-o2.getAge();
int n2=o1.getName().compareTo(o2.getName());
return n1==0?n2:n1;
}
});
Person p1=new Person("xyz",20);
Person p2=new Person("hello",22);
Person p3=new Person("zs",24);
Person p4=new Person("abc",20);
persons.add(p1);
persons.add(p2);
persons.add(p3);
persons.add(p4);
System.out.println(persons.toString());
}
}
import java.util.Comparator;
import java.util.TreeSet;
/**
* 要求:使用TreeSet集合实现字符串按长度进行排序
* Comparator 接口实现定制比较
*/
public class Demo_treesetex {
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("hello world");
treeSet.add("apple");
treeSet.add("beijing");
treeSet.add("hello kitty");
treeSet.add("xian");
treeSet.add("nanjing");
treeSet.add("lisi");
System.out.println(treeSet.toString());
}
}
6、Map接口与实现类
import com.sun.javafx.collections.MappingChange;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
*Map接口的使用
* 特点:存储的是键值对 键不可重复 值可重复 无序
*/
public class Demo1_map {
public static void main(String[] args) {
//1、创建
Map<String,String> map=new HashMap<>();
map.put("cn","中国");
map.put("uk","英国");
map.put("usa","美国");
System.out.println(map.size());
System.out.println(map.toString());
map.put("CN","中国");
map.put("cn","china");
System.out.println(map.size());
System.out.println(map.toString());
//2、删除
map.remove("cn");
System.out.println(map.size());
System.out.println(map.toString());
//3、遍历
//方式一 使用keySet() 得到的是Set集合 可以用迭代器或增强的for循环遍历
System.out.println("----------使用keySet()增强for------------");
Set<String> keyset=map.keySet();
for(String key:keyset){
System.out.println(key+"---"+map.get(key));
}
System.out.println("----------使用keySet()迭代器------------");
Iterator<String> iterator=keyset.iterator();
while(iterator.hasNext()){
String k=iterator.next();
System.out.println(k+"---"+map.get(k));
}
//方法二:使用 entrySet()方法 方法二效率高于方法一
System.out.println("----------使用 entrySet()方法 增强for------------");
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("----------使用 entrySet()方法 迭代器------------");
Iterator<Map.Entry<String,String>> iterator1=entries.iterator();
while (iterator1.hasNext()){
Map.Entry<String,String> k=iterator1.next();
System.out.println(k.getKey()+"-----"+k.getValue());
}
//4、判断
System.out.println(map.containsKey("cn"));
System.out.println(map.containsValue("中国"));
System.out.println(map.isEmpty());
}
}
3
{usa=美国, uk=英国, cn=中国}
4
{usa=美国, uk=英国, cn=china, CN=中国}
3
{usa=美国, uk=英国, CN=中国}
----------使用keySet()增强for------------
usa---美国
uk---英国
CN---中国
----------使用keySet()迭代器------------
usa---美国
uk---英国
CN---中国
----------使用 entrySet()方法 增强for------------
usa----美国
uk----英国
CN----中国
----------使用 entrySet()方法 迭代器------------
usa-----美国
uk-----英国
CN-----中国
false
true
false
(1)Map的实现类
HashMap线程不安全,运行效率快;允许用null作为key或是value。
HashMap源码分析:
①HashMap刚创建时,table是null,为了节省空间,当添加第一个元素时,table容量调整为16;
②当元素个数大于阈值(16*0.75=12)时,会进行扩容,扩容后大为原来的2倍,目的是减少调整元素的个数;
③jdk1.8 当每个链表长度大于8,并且元素个数大于等于64时,会调整为红黑树,目的是提高执行效率;
④jdk1.8 当链表长度小于6时,调整为链表;
⑤jdk1.8 以前,链表时头插入,jdk1.8 之后是尾插入。
import java.util.HashMap;
import java.util.Map;
/**
* HashMap 集合的使用
* 存储结构 : 哈希表 数组加链表 红黑树
* 使用key的hashcode和equals作为重复依据
*/
public class Demo1_HashMap {
public static void main(String[] args) {
HashMap<Student_map,String> hashMap=new HashMap<>();
//刚创建hashmap之后没有添加元素 此时table=null size=0 目的节省空间
Student_map s1=new Student_map("张三",11);
Student_map s2=new Student_map("李四",12);
Student_map s3=new Student_map("王舞",13);
Student_map s4=new Student_map("王陆",14);
hashMap.put(s1,"male");
hashMap.put(s2,"male");
hashMap.put(s3,"female");
hashMap.put(s4,"male");
hashMap.put(new Student_map("王陆",14),"male");
System.out.println(hashMap.size());
System.out.println(hashMap.toString());
hashMap.remove(s1);
System.out.println("删除之后"+hashMap.size());
System.out.println(hashMap.toString());
//遍历
System.out.println("----------使用keySet()增强for------------");
for(Student_map key:hashMap.keySet()){
System.out.println(key.toString()+"="+hashMap.get(key));
}
System.out.println("----------使用 entrySet()方法 增强for------------");
for(Map.Entry<Student_map,String> entry:hashMap.entrySet()){
System.out.println(entry.getKey()+"="+entry.getValue());
}
//判断
System.out.println(hashMap.containsKey(s1));
System.out.println(hashMap.containsValue("male"));
System.out.println(hashMap.containsKey(new Student_map("王陆",14)));
System.out.println(hashMap.isEmpty());
}
}
4
{Student_map{name='王陆', stuNo=14}=male, Student_map{name='王舞', stuNo=13}=female, Student_map{name='张三', stuNo=11}=male, Student_map{name='李四', stuNo=12}=male}
删除之后3
{Student_map{name='王陆', stuNo=14}=male, Student_map{name='王舞', stuNo=13}=female, Student_map{name='李四', stuNo=12}=male}
----------使用keySet()增强for------------
Student_map{name='王陆', stuNo=14}=male
Student_map{name='王舞', stuNo=13}=female
Student_map{name='李四', stuNo=12}=male
----------使用 entrySet()方法 增强for------------
Student_map{name='王陆', stuNo=14}=male
Student_map{name='王舞', stuNo=13}=female
Student_map{name='李四', stuNo=12}=male
false
true
true
false
Hashtable:线程安全,运行效率慢;不允许用null作为key或是value。目前不常用了。
Properties:是Hashtable的子类,要求key和value都是String;通常用于配置文件的读取。
TreeMap:实现了SortedMap接口(是Map的子接口),可以对key自动排序。存储结构红黑树。
import java.util.Map;
import java.util.TreeMap;
/**
* TreeMap的使用
*存储结构:红黑树
*
*/
public class Demo1_TreeMap {
public static void main(String[] args) {
TreeMap<Student_map,String> treeMap=new TreeMap<>();
Student_map s1=new Student_map("张三",11);
Student_map s2=new Student_map("李四",12);
Student_map s3=new Student_map("王舞",13);
Student_map s4=new Student_map("王陆",14);
treeMap.put(s1,"北京");
treeMap.put(s2,"上海");
treeMap.put(s3,"广州");
treeMap.put(s4,"深圳");
treeMap.put(new Student_map("王陆",14),"南京");
System.out.println(treeMap.size());
System.out.println(treeMap.toString());
treeMap.remove(s4);
System.out.println("删除之后:"+treeMap.size());
System.out.println(treeMap.toString());
System.out.println("----------使用keySet()增强for------------");
for(Student_map key:treeMap.keySet()){
System.out.println(key+"----------"+treeMap.get(key));
}
System.out.println("----------使用 entrySet()方法 增强for------------");
for(Map.Entry<Student_map,String> entry:treeMap.entrySet()){
System.out.println(entry.getKey()+"-----"+entry.getValue());
}
System.out.println(treeMap.containsKey(s1));
System.out.println(treeMap.containsValue("北京"));
System.out.println(treeMap.isEmpty());
}
}
4
{Student_map{name='张三', stuNo=11}=北京, Student_map{name='李四', stuNo=12}=上海, Student_map{name='王舞', stuNo=13}=广州, Student_map{name='王陆', stuNo=14}=南京}
删除之后:3
{Student_map{name='张三', stuNo=11}=北京, Student_map{name='李四', stuNo=12}=上海, Student_map{name='王舞', stuNo=13}=广州}
----------使用keySet()增强for------------
Student_map{name='张三', stuNo=11}----------北京
Student_map{name='李四', stuNo=12}----------上海
Student_map{name='王舞', stuNo=13}----------广州
----------使用 entrySet()方法 增强for------------
Student_map{name='张三', stuNo=11}-----北京
Student_map{name='李四', stuNo=12}-----上海
Student_map{name='王舞', stuNo=13}-----广州
true
true
false
7、Collections工具类
Collections工具类:集合工具类,定义了除了存取以外的集合常用方法。
import java.lang.reflect.Array;
import java.util.*;
public class Demo2_Collections {
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,13);
System.out.println(i);
//copy复制
//Exception in thread "main" java.lang.IndexOutOfBoundsException: Source does not fit in dest
//要求两个集合大小得相同 元素个数得一样才能复制
List<Integer> list1=new ArrayList<>();
for(int j=0;j<list.size();j++){
list1.add(0);
}
Collections.copy(list1,list);
System.out.println(list1.toString());
//reverse反转
Collections.reverse(list);
System.out.println("反转之后:"+list.toString());
//shuffle打乱元素顺序
Collections.shuffle(list);
System.out.println("打乱之后:"+list.toString());
//list转成数组
System.out.println("list转化为数组");
Integer[] arr=list.toArray(new Integer[0]);
System.out.println(arr.length);
System.out.println(Arrays.toString(arr));
System.out.println(arr[1]);
//数组转成list 这个集合是个受限集合 不能添加和删除元素
System.out.println("数组转化为list");
String[] names={"王舞","王陆","张三"};
List<String> list2=Arrays.asList(names);
//list2.add("zhang");//不能添加和删除元素 报错Exception in thread "main" java.lang.UnsupportedOperationException
System.out.println(list2);
//把基本类型数组转成集合需要修改为包装类才行
Integer[] nums={100,200,300,400,500};
List<Integer> list3=Arrays.asList(nums);
System.out.println(list3);
}
}