集合:
collection集合框架:
Collections工具类:
Collection集合的基本操作:
package wwl.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
/**
* Collection集合的基本操作
*
*/
public class test01 {
public static void main(String[] args) {
//1.创建Collection集合
//collection是一个接口,需要赋值实现类对象
Collection collection = new ArrayList();
//2.向集合中添加元素,集合中存储引用类型数据,只要Object类型对象就可以添加到集合中
collection.add("abc");
collection.add(456);//添加基本数据类型时,系统会自动装箱为包装类对象再添加到集合中
collection.add(true);
//3.在实际应用中,一个集合中一般只存储一个类型的数据,可以通过泛型约束集合中元素的类型
//泛型就是把数据类型作为参数传递:
Collection<String> collection2 = new ArrayList<String>();//通过泛型约束集合中只能存储String类型的数据
collection2.add("jj");
collection2.add("dd");
collection2.add("mm");
collection2.add("jj");
//collection2.add(123); 通过泛型约束collection2集合只能存储String,添加其他类型数据,就会编译错误
//泛型的好处时在编译时,可以进行数据的检查
//4.直接打印
System.out.println(collection2);
/*当前collection2引用指向的是ArrayList集合的对象
* 在调用println()方法时,把collection2变量的值,即ArrayList对象的引用作为println()方法的实参
* 在println()方法打印对象时,调用的是ArrayList对象的toString()方法
*/
//5.判断:
System.out.println(collection2.isEmpty());
System.out.println(collection2.size());
System.out.println(collection2.contains("dd"));
//6.删除jj
collection2.remove("jj");//只删除第一个匹配的元素
System.out.println(collection2);//[dd, mm, jj]
//7.转换为数组:
String[] myArray = new String[collection2.size()];
collection2.toArray(myArray);
System.out.println(Arrays.toString(myArray));
}
}
Collection集合的迭代器:
package wwl.collection;
import java.util.*;
public class test02 {
public static void main(String[] args) {
Collection<String> collection = new ArrayList<String>();
//添加数据
collection.add("jj");
collection.add("dd");
collection.add("mm");
collection.add("jj");
collection.add("mm");
collection.add("dd");
System.out.println(collection);
//迭代遍历集合的每个元素,collection有一个iterator方法继承来的
//hashNext()判断是否还有下一个元素
//next()返回下个元素,游标下移
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();
System.out.println(string);
}
System.out.println();
//collection.remove()只能删除第一个匹配的元素
collection.remove("jj");
System.out.println(collection);
//删除集合中所有的dd,遍历集合中的元素,是dd就删除
//iterator迭代器的游标,经过while循环后指向了最后一个元素的后边了,需重新获得迭代器对象
iterator = collection.iterator();//游标又指向第一个元素前边
while (iterator.hasNext()) {
String string = (String) iterator.next();
if ("dd".equals(string)) {
iterator.remove();//通过迭代器删除
}
}
System.out.println(collection);
}
}
泛型:
set集合:
package wwl.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* Set集合
*
*/
public class set {
public static void main(String[] args) {
// 1.创建Set集合:
Set<String> set = new HashSet<>();
// 2.添加元素:
set.add("jj");
set.add("dd");
set.add("ee");
set.add("1234565");
set.add("gg");
// 3.直接打印,存储顺序与添加顺序可能不一样
System.out.println(set);//[jj, dd, ee, gg, 1234565]
// 4.添加重复的数据:
set.add("jj");
set.add("gg");//[jj, dd, ee, gg, 1234565],没有添加重复数据
// 5.迭代
Iterator<String> iterator = set.iterator();
while (iterator.hasNext()) {
String string = iterator.next();
System.out.print(string + "\t");
}
System.out.println( );
}
}
package wwl.Set;
/**
* HashSet
* 1.HashSet底层时HashMap
* 2.向hashset中添加元素,实际上是把该元素作为键添加到底层的HashMap中
* 3.HashSet就是HashMap键的集合
*
*/
public class HashSet {
public static void main(String[] args) {
java.util.HashSet<String> hashSet = new java.util.HashSet<>();
hashSet.add("ggg");
}
}
TreeSet集合:
package wwl.Set;
import java.util.Comparator;
import java.util.TreeSet;
/**
* TreeSet
* 1.TreeSet实现了SortedSet接口,可以对元素自然排序,要求集合中的元素必须是可比较的
* (1.)在创建TreeSet时,可以指定Comperator比较器
* (2.)没有指定Comparator比较器,要求元素的类实现Comparable接口
* 2.TreeSet底层是TreeMap
* 向TreeSet添加元素,实际上是把该元素作为键添加到了底层的TreeMap中
* TreeSet实际上就是TreeMap键的集合
*/
public class Test02 {
public static void main(String[] args) {
// 1.创建TreeSet集合,存储String,按姓名降序排序,指定Comparator比较器
TreeSet<String> treeSet = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
treeSet.add("xx");
treeSet.add("dd");
treeSet.add("jj");
treeSet.add("oo");
treeSet.add("gg");
//打印集合按字符串降序排序
System.out.println(treeSet);
// 2.创建TreeSet集合,如果没有指定Comparator比较器,要求元素的类实现Comparable接口
//TreeSet存储String类型字符串,String实现了Comparable接口
TreeSet<String> treeSet2 = new TreeSet<String>();
treeSet2.addAll(treeSet); //把treeset集合中的元素都添加到treeset2中
System.out.println(treeSet2);//[dd, gg, jj, oo, xx]
}
}
TreeSet集合添加自定义类型数据:
package wwl.Set;
/**
* 产品类
*
*/
public class Product implements Comparable<Product> {
private String name;
private int amount;
private double price;
public Product() {
super();
// TODO Auto-generated constructor stub
}
public Product(String name, int amount, double price) {
super();
this.name = name;
this.amount = amount;
this.price = price;
}
//重写comparable接口的抽象方法,指定一个比较规则
@Override
public int compareTo(Product o) {
return o.amount - this.amount; //根据数量降序,参数对象大返回正数
}
@Override
public String toString() {
return "Product [name=" + name + ", amount=" + amount + ", price=" + price + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + amount;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(price);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Product other = (Product) obj;
if (amount != other.amount)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(price) != Double.doubleToLongBits(other.price))
return false;
return true;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
package wwl.Set;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
import wwl.array.product;
/**
* 1.TreeSet要求元素是可比较的,TreeSet集合先看是否有Comparator比较器,
* 如果没有comparator比较器,再查找元素的类是否实现了Comparable接口
*
* 2.程序员如何选择Comparator还是Comparable??
* 一般情况下,类实现Comparable接口定义一个默认的比较规则
* 可以通过Comparator定义很多不同的比较规则
*
* 3.在TreeSet集合中,判断是否同一个对象根据comparator/comparable的比较结果是否为0进行判断的
* 如果两个元素的比较结果为0就认为是同一个元素
*
*/
public class Test05 {
public static void main(String[] args) {
//创建TreeSet集合,存储Product产品,默认按价格升序排序,向集合中添加一些Product对象
//在创建TreeSet集合时,可以指定Comparator比较器
TreeSet<Product> treeSet = new TreeSet<>(new Comparator<Product>() {
@Override
public int compare(Product o1, Product o2) {
if(o1.getPrice() - o2.getPrice() > 0) {
return 1;
}else if(o1.getPrice() - o2.getPrice() < 0){
return -1;
}else {
return 0;
}
}
});
//如果在创建TreeSet集合时,没有指定comparator比较器,要求元素的类实现comparable接口
// TreeSet<Product> treeSet = new TreeSet<>();
treeSet.add(new Product("lenovo", 1000, 6800.0));
treeSet.add(new Product("xiaomi", 500, 4800.0));
treeSet.add(new Product("mac", 10, 16800.0));
treeSet.add(new Product("dell", 100, 8800.0));
//把集合中的product打印出来
Iterator<Product> iterator = treeSet.iterator();
while (iterator.hasNext()) {
Product product = iterator.next();
System.out.println(product);
}
Product asus = new Product("Asus", 123 , 4800);
//注意:TreeSet集合不能存储重复的元素,即集合中已经存在该元素,不在添加重复数据
//当前treeset集合根据价格比较,如果两个Product对象价格一样,就认为是同一个对象
//现在集合中xiaomi的价格是4800,刚添加的asus价格也是4800,价格一样,就认为该对象已存在
treeSet.add(asus);
System.out.println(treeSet.size()); //4个
System.out.println(treeSet);//asus没有加进去
System.out.println(treeSet.contains(asus));//true
}
}
List集合的基本使用:
package wwl.collection;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* List集合的集合使用
* List接口继承了collection接口
* List集合为每个元素制定了一个索引值,主要增加了对索引值的操作
*
*/
public class test03 {
public static void main(String[] args) {
//创建List集合,List是一个接口,List接口的引用需要赋值实现类对象
List<String> list = new ArrayList<String>();
//添加数据:
list.add("jj");
list.add("gg");
list.add("dd");
list.add("mm");
list.add("mm");
list.add("mm");
//List集合是有序的,可重复的,存储顺序和添加顺序一样
System.out.println(list);//[jj, gg, dd, mm, mm, mm]
//判断
System.out.println(list.size());
System.out.println(list.contains("gg"));
System.out.println(list.isEmpty());
//删除第一个jj
list.remove("jj");
//迭代
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();
System.out.print(string + "\t");
}
//迭代删除所有的mm
iterator = list.iterator();
while (iterator.hasNext()) {
String string = (String) iterator.next();
if ("mm".equals(string)) {
iterator.remove();
}
}
System.out.println();
System.out.println(list);
//在指定索引值添加数据
list.add(0,"NN");
list.add(list.size(),"GG");
System.out.println(list);//[NN, gg, dd, GG]
//删除指定位置元素
list.remove(1);
System.out.println(list);//[NN, dd, GG]
//返回元素第一次出现的位置
System.out.println(list.indexOf("dd"));
System.out.println(list.lastIndexOf("GG"));
System.out.println();
//返回指定位置的元素
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}
List存储自定义类型数据需要重写equals方法:
package wwl.collection;
/**
* 创建一个学生管理类:
* 通过List集合存储学生的信息
* 添加学生
* 查找学生
* 删除学生
*
*/
public class test04 {
public static void main(String[] args) {
StudentManager manager = new StudentManager();
//添加学生
manager.add(new Student("lisi",18,80));
manager.add(new Student("wangwu",48,60));
manager.add(new Student("chenqi",38,90));
manager.add(new Student("yanming",28,8));
//显示:
manager.showInfo();
//判断是否有yanming同学
System.out.println(manager.contains(new Student("yanming",28,8)));
manager.delete(new Student("yanming",28,8));
manager.showInfo();
}
}
package wwl.collection;
public class Student {
String name;
int age;
int score;
public Student() {
super();
// TODO Auto-generated constructor stub
}
public Student(String name, int age, int score) {
super();
this.name = name;
this.age = age;
this.score = score;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", score=" + score + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + score;
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 (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (score != other.score)
return false;
return true;
}
}
package wwl.collection;
import java.util.ArrayList;
import java.util.List;
/**
* List集合中contains() / remove()等方法,需要调用对象的equals()方法!
* 如果集合中存储的是自定义类型对象,需要重写equals()方法!
*
*/
public class StudentManager {
//定义一个List集合,保存学生的信息
List<Student> list;
public StudentManager() {
list = new ArrayList<Student>();
}
//添加学生
public void add(Student stu) {
list.add(stu);
}
//删除学生
public void delete(Student stu) {
list.remove(stu);
}
//判断学生是否存在
public boolean contains(Student stu) {
return list.contains(stu);
}
//显示学生的信息
public void showInfo() {
//遍历集合,显示每个学生
for (Student student : list) {
System.out.println(student);
}
}
}
List集合可以排序:
collection工具类里有一个sort方法也可以排序
List的集合类ArrayList和Vector:
移位运算
List集合类LinkedList:
LinkedList底层是双向链表
单向链表:
双向链表:
LinkedList相对于其他集合新增的方法:
package wwl.collection;
import java.util.LinkedList;
/**
* ListedList
*
*/
public class test05 {
public static void main(String[] args) {
LinkedList<String> linkedList = new LinkedList<String>();
linkedList.add("lisi");
linkedList.add("wangwu");
linkedList.add("chenqi");
System.out.println(linkedList);
//分别在头部和尾部添加元素
linkedList.addFirst("laowu");
linkedList.addLast("yangming");
System.out.println(linkedList);//[laowu, lisi, wangwu, chenqi, yangming]
//返回第一个元素,最后一个元素
System.out.println(linkedList.getFirst());
System.out.println(linkedList.getLast());
//删除第一个元素最后一个元素,在remove()删除时,会把删除的元素返回
System.out.println(linkedList.removeFirst());//laowu
System.out.println(linkedList.removeLast());//yangming
System.out.println(linkedList);//[lisi, wangwu, chenqi]
//模拟栈(后进先出)
linkedList.push("xxxx");
System.out.println(linkedList);
System.out.println(linkedList.pop());
//模拟队列(先进先出)
linkedList.offer("oooooo");
System.out.println(linkedList);
System.out.println(linkedList.poll());
}
}
List集合练习:
package wwl.Set;
/**
Students类
*/
public class Students {
private String id;
private String name;
private int score;
public Students(String id, String name, int score) {
super();
this.id = id;
this.name = name;
this.score = score;
}
public Students() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Students [id=" + id + ", name=" + name + ", score=" + score + "]";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + score;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Students other = (Students) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (score != other.score)
return false;
return true;
}
}
package wwl.Set;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
/**
* List集合练习:
* "01,勇哥,100;02,杜哥,95;03,明哥,90;04,菲菲,5;05,杨哥,60"
*
*/
public class Test04 {
public static void main(String[] args) {
String text = "01,勇哥,100;02,杜哥,95;03,明哥,90;04,菲菲,5;05,杨哥,60";
// 1.分离字符串:
String[] words = text.split("[,;]");
// 2.创建List集合,根据分离出来的学生信息创建学生对象,添加到List中
List<Students> list = new ArrayList<>();
//遍历words数组中的内容,创建Students对象,保存到list对象中
for(int i = 0; i< words.length; i+=3) {
Students stu = new Students();
stu.setId(words[i]);
stu.setName(words[i+1]);
stu.setScore(Integer.parseInt(words[i+2]));//将int转为字符串
list.add(stu);
}
//3.通过迭代分别打印集合中学生的信息
Iterator<Students> iterator = list.iterator();
while (iterator.hasNext()) {
Students students = iterator.next();
System.out.println(students);
}
//4.判断集合中是否存在姓名为“明哥”的学生
boolean mingExist = false;
//遍历集合中所有的Students对象,如果有某个对象的姓名与明哥一样,就修改为true
for (Students students : list) {
if("明哥".equals(students.getName())) {
mingExist = true;
break;
}
}
if(mingExist) {
System.out.println("有");
}else {
System.out.println("无");
}
//5.对集合中的学生按成绩降序排序
list.sort(new Comparator<Students>() {
//在匿名内部类中重写接口的抽象方法
@Override
public int compare(Students o1, Students o2) {
return o2.getScore()-o1.getScore();
}
});
//6.通过循环打印集合中学生的信息
for(int i = 0 ; i < list.size(); i++) {
System.out.println(list.get(i));
}
//7.删除名为“明哥的学生”
iterator = list.iterator();
while (iterator.hasNext()) {
Students students = iterator.next();
if("明哥".equals(students.getName())) {
iterator.remove(); // 迭代删除
}
}
//8.打印出来
System.out.println();
for (Students students : list) {
System.out.println(students);
}
}
}
List集合中的元素是Map类型数据:
小结:
Map概述:
map的基本操作:
package wwl.map;
import java.io.ObjectOutputStream.PutField;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import wwl.Set.set;
/**
* map的基本使用
*
*/
public class test01 {
public static void main(String[] args) {
// 1.创建Map集合,存储<员工姓名,工资>
// Map是一个接口
Map<String, Integer> map = new HashMap<>();
// 2.添加数据,Put(k,v)
map.put("yong", 100000);
map.put("du", 50000);
map.put("feifei", 40000);
map.put("ming", 3000);
// 3.直接打印,存储顺序与添加顺序可能不一样
System.out.println(map);//{du=50000, ming=3000, yong=100000, feifei=40000}
// 4.put添加数据时,键已存在
map.put("ming", 3001);//键已存在,使用新的值3001替换原来的值
System.out.println(map);//{du=50000, ming=3001, yong=100000, feifei=40000}
// 5.判断
System.out.println(map.size()); //4 键值对的数量
System.out.println(map.containsKey("yong"));//true
System.out.println(map.containsKey("zhang"));//false
System.out.println(map.containsKey(100000));//true
System.out.println(map.containsKey(3000));//false
// 6.feifei的工资
System.out.println(map.get("feifei")); //40000
System.out.println(map.get("zhang")); //null,键不存在
// 7.修改替换
map.replace("ming", 3003);
System.out.println(map);
map.replace("zhang", 88888);//当前map中不存在zhang这个键
System.out.println(map);
// 8.删除:
map.remove("yong"); //只要键匹配,就把键值对删除
System.out.println(map);
map.remove("ming", 3000); //要求<ming,3000>键值对都匹配才会删除
System.out.println(map);
// 9.返回所有键的结果:
Set<String> keySet = map.keySet();
System.out.println(keySet);//[du, ming, feifei]
// 10.返回所有值的集合
Collection<Integer> values = map.values();
Iterator<Integer> iterator = values.iterator();
while (iterator.hasNext()) {
Integer integer = iterator.next();
System.out.println(integer + "\t");
}
System.out.println();//50000 3003 40000
// 11.返回所有Entry的集合
Set<Entry<String, Integer>> entrySet = map.entrySet();
for (Entry<String, Integer> entry : entrySet) { //du:50000 ming:3003 feifei:40000
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
Map练习统计字符出现的次数:
第一种:
package wwl.map;
import java.util.HashMap;
import java.util.Map;
/**
* 1.统计每个字符出现的次数
* a:3
* b:3
* c:6
*
* 2.输出字符x出现的次数
*
*
*/
public class test02 {
public static void main(String[] args) {
String text = "aaabbbdddccccccgfhgjghkjgxxhjkgxxhxxxk";
int a = 0,b = 0, c = 0,x = 0;
//1.定义一个Map保存<字符,次数>
Map<Character, Integer> map = new HashMap<>();
//2.遍历字符串每个字符
//2.1如果该字符第一次出现(map中的键不包含该字符),把<字符,1>添加到map中
//2.2如果该字符不是第一次出现,把map中该字符的次数取出来加1再保存到map中
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
if(ch == 'a') {
map.put(ch, a);
map.get(a++);
}else if(ch == 'b') {
map.put(ch, b);
map.get(b++);
}else if(ch == 'c') {
map.put(ch, c);
map.get(c++);
}else if(ch == 'x'){
map.get(x++);
}
}
//3.打印结果:
System.out.println("a:" + a + "\t" + "b:" + b + "\t" + "c:" + c + "\t" + "x:" + x);
}
}
第二种(需要掌握):
package wwl.map;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* 1.统计每个字符出现的次数(另一种写法)
* a:3
* b:3
* c:6
*
* 2.输出字符x出现的次数
*
*/
public class test03 {
public static void main(String[] args) {
String text = "aaabbbdddccccccgfhgjghkjgxxhjkgxxhxxxk";
//1.定义一个Map保存<字符,次数>
Map<Character, Integer> map = new HashMap<>();
//2.遍历字符串每个字符
for (int i = 0; i < text.length(); i++) {
char ch = text.charAt(i);
//2.1如果该字符第一次出现(map中的键不包含该字符),把<字符,1>添加到map中
if(! map.containsKey(ch)) {
map.put(ch, 1);
}else {
//2.2如果该字符不是第一次出现,把map中该字符的次数取出来加1再保存到map中;
//总的来说就是没有先创建一个键值对来存储,后来有的把次数取出来叠加再放回去!!
int count = map.get(ch);
map.replace(ch, count+1);
}
}
//3.打印结果:
Set<Entry<Character, Integer>> entrySet = map.entrySet();
for (Entry<Character, Integer> entry : entrySet) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
Set + Map练习统计邮箱的个数:
package wwl.map;
import java.lang.reflect.Array;
import java.util.*;
import java.util.Map.Entry;
/**
* Set + Map练习,统计邮箱的个数
*
*/
public class test04 {
public static void main(String[] args) {
String text = "yang@163.com,ming@163.com,du@sohu.com,yong@sohu.com,zhang@qq.com,feifei@sohu.com";
//把字符串的邮箱分离出来:
String[] words = text.split("[,@]");
System.out.println(Arrays.toString(words));//[yang, 163.com, ming, 163.com, du, sohu.com, yong, sohu.com, zhang, qq.com, feifei, sohu.com]
//分别把邮箱名和邮箱地址保存到一个Map中<yang,163.com>
//把这些map再保存到Set集合
Set<Map<String, String>> set = new HashSet<>();
for (int i = 0; i < words.length; i+=2) {
Map<String, String> map = new HashMap<String, String>();
map.put(words[i], words[i+1]);
set.add(map);
}
System.out.println(set);
//统计每个邮箱地址的数量:<邮箱,数量> <sohu.com,2>
Map<String, Integer> map2 = new HashMap<String, Integer>();
for (int i = 1; i < words.length; i+=2) {
//判断邮箱地址是否在map中,如果不在,添加<邮箱地址,1>
if(! map2.containsKey(words[i])) {
map2.put(words[i], 1);
}else {
//如果已在map中,把原来的次数取出来+1
int count = map2.get(words[i]);
map2.replace(words[i], count+1);
}
}
//输出map2
Set<Entry<String, Integer>> entrySet = map2.entrySet();
for (Entry<String, Integer> entry : entrySet) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
}
HashMap工作原理:
HashTable 与 HashMap(面试需要记):
HashTable的子类Properties(常用)+加载配置文件:
package wwl.map;
import java.util.Properties;
/**
* Properties
* 继承了HashTable
* 它的键与值都是String字符串
* 常用于设置读取系统属性值
* 常用的两个方法:SetProperty(属性名,属性值) getProperty(属性名)
*
*/
public class test05 {
public static void main(String[] args) {
//创建Properties对象时不需要泛型,都是字符串
Properties properties = new Properties();
//设置属性
properties.setProperty("username", "wwl");
properties.setProperty("password", "123");
//读取系统属性:
System.out.println(properties.get("username"));
System.out.println(properties.get("password"));
}
}
package wwl.map;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* 1.经常把属性保存到配置文件中
* 2.一般情况下,会在当前工程中单独创建一个资源包,在该包中添加配置文件,配置文件的后缀名是.properties
* 在src目录中.java源文件自动编译为.class文件保存到bin目录中,src目录中非.java源文件自动复制到bin目录中
* 3.可以使用Properties读取配置文件的属性
*
*/
public class test06 {
public static void main(String[] args) throws IOException {
//创建Properties对象
Properties properties = new Properties();
//加载配置文件
//适用于单线程
// InputStream inStream = test06.class.getResourceAsStream("/resources/config.properties");
//适用于多线程
InputStream inStream =Thread.currentThread().getContextClassLoader().getResourceAsStream("resources/config.properties");
properties.load(inStream);//如果出现空指针异常,一般是源文件路径不正确;
//读取配置信息
System.out.println(properties.getProperty("username"));
System.out.println(properties.get("password"));
}
}
package wwl.map;
import java.util.ResourceBundle;
/**
* 使用ResouceBundle加载配置文件
*
*/
public class test07 {
public static void main(String[] args) {
//加载资源时,不需要扩展名(前提是配置文件的扩展名必须是properties)
ResourceBundle bundle = ResourceBundle.getBundle("resources/config");
System.out.println(bundle.getString("username"));
System.out.println(bundle.getString("password"));
}
}
TreeMap
package wwl.map;
import java.util.Comparator;
import java.util.TreeMap;
/**
* TreeMap
* TreeMap的键可以是自定义的类,但是很少见
*/
public class test08 {
public static void main(String[] args) {
//1.定义TreeMap保存<姓名,工资>要求根据姓名降序排序
//在创建TreeMap时可以根据comparator比较器
TreeMap<String, Integer> treeMap = new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
treeMap.put("yong", 10000);
treeMap.put("du", 5000);
treeMap.put("zhang", 8000);
treeMap.put("feifei", 4000);
treeMap.put("ming", 1000);
System.out.println(treeMap);
//创建Treemap,如果没有通过构造方法指定comparator比较器,根据Map中的键要实现Comparable接口
TreeMap<String, Integer> treeMap2 = new TreeMap<>();
treeMap2.putAll(treeMap);//把treemap中所有<键,值>对都添加到treeMap2中
System.out.println(treeMap2);//默认升序
}
}
Map小结:
练习使用集合实现军队练习:
运行类
package wwl.collection;
/**
* 定义一个Attackable攻击接口,封装attach()攻击行为
* 定义一个Movable接口,封装move()移动的行为
* 定义一个Weapon武器库,武器是可攻击的,但是不同武器攻击方式不同
* 定义一个Tank类Weapon,坦克是可移动的
* 定义一个Flighter战斗机类继承Weapon,战斗机也是可移动的
* 定义一个Missile导弹类继承Weapon,导弹不能移动
* 定义一个Army军队类,军队有武器库,使用数组来保存若干的武器模拟武器库;向武器库中添加武器,从武器库中删除武器
*
*/
public class exercise {
public static void main(String[] args) {
Army army = new Army();
army.addWeapon(new Missile("东风-10A"));
army.addWeapon(new Flighter("歼-20"));
army.addWeapon(new Tank("99坦克"));
army.moveAll();
System.out.println("-------------");
army.attackAll();
army.deleteWeapon(new Tank("99坦克"));
army.showInfo();
}
}
攻击接口
package wwl.collection;
//攻击接口
public interface Attackable {
void attack();
}
移动接口:
package wwl.collection;
//移动接口
public interface Movable {
void move();
}
导弹类:
package wwl.collection;
/**
* 定义一个Missile导弹类继承Weapon,导弹不能移动
*/
public class Missile extends Weapon {
public Missile(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void attack() {
System.out.println(name + "导弹实施远程打击");
}
}
武器库实现类:
getClass获取类名 getSimpleName获取简易类名
package wwl.collection;
/**
* 定义一个Weapon武器库,武器是可攻击的,但是不同武器攻击方式不同
* 但是不同的武器攻击方式不同,武器类没法重写attack()方法,把Weapon武器类定义为抽象类
*
*/
public abstract class Weapon implements Attackable {
String name;
public Weapon(String name) {
super();
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public String toString() {
//******getClass获取类名 getSimpleName获取简易类名*******
return this.getClass().getSimpleName() + "[name=" + name + "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Weapon other = (Weapon) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
军队类
instanceof通过返回一个布尔值来指出,这个对象是否是这个特定类或者是它的子类的一个实例。
package wwl.collection;
/**
* 定义一个Army军队类,军队有武器库,使用数组来保存若干的武器模拟武器库;向武器库中添加武器,从武器库中删除武器
* 给所有武器下达攻击指令,能给移动的武器下达移动指令
*
*/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Army {
Collection<Weapon> wepaponStorage;//武器库
public Army() {
wepaponStorage = new ArrayList<Weapon>();
}
//向武器库添加武器
public void addWeapon(Weapon w) {
wepaponStorage.add(w);
}
//从武器库删除武器
public void deleteWeapon(Weapon w) {
wepaponStorage.remove(w);
}
// 给所有武器下达攻击指令
public void attackAll() {
//遍历武器库所有武器调用attack()方法
for (Weapon weapon : wepaponStorage) {
weapon.attack();
}
}
//给移动的武器下达移动指令
public void moveAll() {
for (Weapon weapon : wepaponStorage) {
//给移动的武器下达移动指令
if(weapon instanceof Movable) {
((Movable) weapon).move();//强转接口
}
}
}
public void showInfo() {
Iterator<Weapon> iterator = wepaponStorage.iterator();
while (iterator.hasNext()) {
Weapon weapon = (Weapon) iterator.next();
System.out.println(weapon);
}
}
}
坦克:
package wwl.collection;
/**
* 坦克类是一个武器,可以移动
* 在继承Weapon武器类的同时,实现了Movable接口
*
*/
public class Tank extends Weapon implements Movable {
public Tank(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void attack() {
System.out.println(name + "坦克发射炮弹······");
}
@Override
public void move() {
System.out.println(name + "坦克实施突袭");
}
}
飞机:
package wwl.collection;
public class Flighter extends Weapon implements Movable {
public Flighter(String name) {
super(name);
// TODO Auto-generated constructor stub
}
@Override
public void attack() {
System.out.println(name + "战斗机实施空对空打击");
}
@Override
public void move() {
System.out.println(name + "战斗机起飞,实施远距离奔袭");
}
}