1. 容器概念:
Collection接口: Set 、List 、Map
Set:HashSet
List:ArrayList 、 LinkedList 、 Vector
Map: HashMap、HashTable 、Properties
List接口:有顺序,可以重复
ArrayList: 底层数组实现,线程不安全,效率高,查询快,修改,插入、删除慢
LinkedList: 底层链表实现,线程不安全,查询慢,修改、删除、插入块
Vector: 底层数组实现,线程安全,效率低
Set: 容器中元素没有顺序,而且不能重复
.equals: 比较对象的内容是否相当
=: 地址是否相同
HashMap与HashTable:
HashMap 线程不安全,效率高, 键最多一个null,值最多可以多个null
HashTable 线程安全,效率低下, 键与值不能为null
Iterator接口: 游标
Iterator对象作为迭代器, 可以方便的实现对容器内部元素的遍历
hastNext() // 是否有元素没有变遍历
next() // 返回游标当前位置,并且把游标移动到下一个位置
remove() // 删除游标左面的元素,执行完成 next 之后改操作 执行执行一次
foreach 增强for实现就是通过实现 Iterator 接口
2.Java 排序规则
基本数据类型:数据,按照日常大小排序
Date(): 按照时间戳
字符串: 首先按照长度,长度相同按照首字母排序
自定义类:Comparable 接口实现 实体类继承
Comparator: 独立于实体类
排序算法: 冒泡、选择排序
/*
* 1. 冒泡排序
* 2. Java Jdk 提供排序函数 sort
* 自定排序: 类实现Comparable 接口
* 提供Comparator 排序器
*
*/
@Test
public void main00(){
boolean sorted =true;
// 冒号排序,一趟确定最大数排到第一位
int[] list= { 1,2,3,4,5 }; // 6 个元素11144
for (int i = 0; i < list.length-1; i++) { // 需要走 5 趟
sorted=true ; // 假定有序,,冒泡排序优化版,如果有序,那么一趟都不走
for (int j = 0; j < list.length-i-1; j++) { // 每一趟把最小元素排在最后面
if(list[j]>list[j+1]){
int temp= list[j+1];
list[j+1]=list[j];
list[j]= temp;
sorted=false;
}
}
if(sorted){
break;
}
System.out.println(Arrays.toString(list));
/**
* [5, 6, 4, 3, 100, 1]
[6, 5, 4, 100, 3, 1]
[6, 5, 100, 4, 3, 1]
[6, 100, 5, 4, 3, 1]
[100, 6, 5, 4, 3, 1]
*/
}
System.out.println("最终排序结果:"+Arrays.toString(list));
// 时间降序+ 点击量升序+ 标题降序
// NewItem 实现 Comparable 接口
List<NewItem> news=new ArrayList<NewItem>();
news.add(new NewItem("b",50,new Date(System.currentTimeMillis()-1000*60*60)));
news.add(new NewItem("a",100,new Date()));
news.add(new NewItem("b",60,new Date(System.currentTimeMillis()-1000*60*60)));
// 排序, 类自定义排序, sort 默认是升序
Collections.sort(news);
System.out.println(news);
// 提供排序器 Comparator, 按照价格排序
List<Goods> listGoods =new ArrayList<Goods>();
listGoods.add(new Goods("老a视频",100,2000));
listGoods.add(new Goods("老b视频",50,2000));
listGoods.add(new Goods("老c视频",1000,1000));
Collections.sort(listGoods, new Comparator<Goods>() {
@Override
public int compare(Goods o1, Goods o2) {
return -(o1.getPrice()-o2.getPrice()>0?1:(o1.getPrice()==o2.getPrice()?0:-1));
}
});
System.out.println(listGoods);
}
package com.denganzhi.tip;
import java.util.Date;
public class NewItem implements Comparable<NewItem>{
// 标题
private String title;
// 点击量
private int hits;
// 时间
private Date pubTime;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getHits() {
return hits;
}
public void setHits(int hits) {
this.hits = hits;
}
public Date getPubTime() {
return pubTime;
}
public void setPubTime(Date pubTime) {
this.pubTime = pubTime;
}
public NewItem() {
super();
}
public NewItem(String title, int hits, Date pubTime) {
super();
this.title = title;
this.hits = hits;
this.pubTime = pubTime;
}
// 时间降序+ 点击量升序+ 标题降序
@Override
public int compareTo(NewItem o) {
int result =0;
//比较 时间
result =-this.pubTime.compareTo(o.pubTime); //降序
if(0==result){ //时间相同
//点击量
result =this.hits-o.hits; //升序
if(0==result){ //点击量相同
//标题
result=-this.title.compareTo(o.title);//降序
}
}
return result;
}
@Override
public String toString() {
return "NewItem [title=" + title + ", hits=" + hits + ", pubTime=" + pubTime + "]";
}
}
package com.denganzhi.tip;
public class Goods {
//商品名称
private String name;
//价格
private double price;
//收藏量
private int fav;
public Goods() {
}
public Goods(String name, double price, int fav) {
super();
this.name = name;
this.price = price;
this.fav = fav;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getFav() {
return fav;
}
public void setFav(int fav) {
this.fav = fav;
}
@Override
public String toString() {
return "商品名:"+name+",收藏量"+this.fav+",价格:"+this.price+"\n";
}
}
3.HashMap应用: 实现分拣法实现统计出现次数
class Letter{
int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
@Override
public String toString() {
return "Letter [count=" + count + "]";
}
}
// 使用分拣法 实现统计 单词次数
public class ListSetHash {
// 使用分拣法 实现统计 单词次数
@Test
public void main0(){
String str="this is a xiaoming xiaoming this";
String[] strArray= str.split(" ");
/**
* 实现功能: 分拣法, 分拣放入一个类中 统计数据
*/
Map<String,Letter> map=new HashMap<>();
for (String string : strArray) {
// 1. 为所有的key 创建 容器
if(!map.containsKey(string)){
map.put(string, new Letter());
}
Letter col= map.get(string);
col.setCount(col.getCount()+1);
}
System.out.println(map);
}
}
4. Set:容器中元素没有顺序,而且不能重复
TreeSet:插入容器中元素,必须可以排序,提供Comparator 比较器
/**
* Java中Set、TreeSet 使用
*/
@Test
public void main1(){
Person p1=new Person("小明",20);
Person p2=new Person("小黑",30);
Person p3=new Person("小泽",10);
Person p4=new Person("小泽",10);
// HashSet 内容无序,add的内容会自动重写equals方法,不允许出现相同的元素
Set<Person> set1=new HashSet<>();
set1.add(p1);
set1.add(p2);
set1.add(p4);
System.out.println("set1..."+set1);
// Set遍历方式使用 Iterator
Iterator<Person> pSet1= set1.iterator();
while(pSet1.hasNext()){
Person person= pSet1.next();
pSet1.remove();
// System.out.println("person:"+person);
}
// Set 遍历 方式使用 for-each
for (Person person : set1) {
System.out.println("for:"+ person);
}
System.out.println("-------set------");
// TreeSet 按照年龄升序 ,提供比较器, 必须有序插入内容
TreeSet<Person> persons=new TreeSet<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
// TODO Auto-generated method stub
return -(o1.getAge()-o2.getAge());
}
});
persons.add(p1);
persons.add(p2);
persons.add(p3);
System.out.println(persons);
}
类实现Comparable接口
/**
* 类实现 Comparable 接口,插入 TreeSet 集合中
*/
@Test
public void main2(){
// TreeSet key 可以排序,实现接口 Comparable
Person2 p1=new Person2("小明",20,10000);
Person2 p2=new Person2("小黑",30,14000);
Person2 p3=new Person2("小泽",10,11000);
TreeSet<Person2> person2=new TreeSet<>();
person2.add(p1);
person2.add(p2);
person2.add(p3);
System.out.println(person2);
}
Person2类
package com.denganzhi.tip;
public class Person2 implements Comparable<Person2> {
private String name;
private int age;
private int salary;
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;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public Person2(String name, int age, int salary) {
super();
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public int compareTo(Person2 o) {
// TODO Auto-generated method stub
return this.age>o.age?1:(this.age == o.age?0:-1);
}
@Override
public String toString() {
return "Person2 [name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
}
5. TreeMap key 可以排序
// TreeMap key 可以排序
@Test
public void main3(){
Person p1=new Person("小明",20);
Person p2=new Person("小黑",30);
Person p3=new Person("小泽",10);
TreeMap<Person, String> map=new TreeMap<>(new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
// TODO Auto-generated method stub
return o1.getAge()-o2.getAge();
}
});
map.put(p1, "a");
map.put(p2, "b");
map.put(p3, "c");
// 查看键
Set<Person> persons= map.keySet();
System.out.println(persons);
}
Person类代码:
package com.denganzhi.tip;
public class Person {
private String name;
private int 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;
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
}
6.Collections方法收集:
* binarySearch 必须升序
* sort(List<T> list):
* sort(List<T> lit,Comparotor<? super T> c)
* reverse
* shuffle
* swap
/*** Collections方法收集:
* binarySearch 必须升序
* sort(List<T> list):
* sort(List<T> lit,Comparotor<? super T> c)
* reverse
* shuffle
* swap
*/
@Test
public void main4(){
// 二分法查找,容器可以有序,否则异常
List<Integer> list=new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
// 反转
// Collections.reverse(list);
// System.out.println(list);
int result=Collections.binarySearch(list,5);
System.out.println(result);
// 洗牌
Collections.shuffle(list);
System.out.println(list);
}
6. properties 是hashtable的子类
用于存储配置 文件 .jdbc .xml到本地
从本地读取 .jdbc .xml 读取配置文件
/**
* properties 是hashtable的子类
* 用于存储配置 文件 .jdbc .xml到本地
* 从本地读取 .jdbc .xml 读取配置文件
*/
@Test
public void main111() throws FileNotFoundException, IOException{
// 创建 对象
// properties properties=new Properties();
// // 存储
// properties.setProperty("driver", "oracle.jdbc.OracleDriver");
// properties.setProperty("user", "xiaoming");
// properties.setProperty("password", "123456");
// // 写入资源配置文件 , 绝对路径
// properties.store(new FileOutputStream(new File("e:\\oracle.jdbc")), "db配置");
// // 当前工程下,相对路径
// properties.storeToXML(new FileOutputStream(new File("oracle.xml")), "db配置");
// System.out.println(properties.get("password"));
// 加载
Properties properties2=new Properties();
properties2.load(new FileReader(new File("oracle.jdbc")));
System.out.println(properties2.getProperty("driver"));
// 类加载器 获取路径 getResourceAsStream("") 空表示 bin 路径路径下
properties2.load(ListSetHash.class.getResourceAsStream("/com/denganzhi/tip/oracle.xml"));
System.out.println(ListSetHash.class.getResourceAsStream("/com/denganzhi/tip/oracle.xml"));
System.out.println(properties2.getProperty("driver"));
}
7、 ArrayDeque 容器, 栈, 先进先出
ArrayDeque 容器,队列,先进先出
App 到 蓝牙发送队列设计
package com.denganzhi.pp;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Queue;
class MyStack<E> {
//容器, 栈, 先进后出
// private Deque<E> container =new ArrayDeque<E>();
// 容器,队列,先进先出
private Queue<E> container =new ArrayDeque<E>();
//容量
private int cap;
public MyStack(int cap) {
super();
this.cap = cap;
}
//压栈
public boolean push(E e){
if(container.size()+1>cap){
return false;
}
for (E str : container) {
if(( (byte[])str)[3] == ((byte[])e)[3] ){
// System.out.println("1:"+((byte[])str)[3]);
// System.out.println("2:"+ ((byte[])str)[3]) ;
return false;
}
// System.out.println("----:"+((byte[])str)[3]);
}
// System.out.println(((byte[])(e))[3]);
// 相当于 List的 Add方法
return container.offer(e);
}
//弹栈
public E pop(){
// 相当于List的 remove 方法
return container.poll();
}
//获取
public E peek(){
// 相当于List的 get方法
return container.peek();
}
public int size(){
return this.container.size();
}
public void show(){
for (E str : container) {
System.out.println("----:"+((byte[])str)[3]);
}
}
}
public class StackTest {
public static void main0001(String[] args) {
// 模拟器蓝牙数据包发送
// 默认保存10条数据,不能放入重复命令,如果已经满了,那么丢弃
MyStack<byte[]> backHistory =new MyStack<byte[]>(10);
for (int i = 0; i < 10 ; i++) {
byte[] b1=new byte[20];
b1[3]=0x03;
}
byte[] b1=new byte[20];
b1[3]=0x03;
byte[] b2=new byte[20];
b2[3]=0x04;
byte[] b3=new byte[20];
b3[3]=0x05;
byte[] b4=new byte[20];
b4[3]=0x05;
byte[] b5=new byte[20];
b5[3]=0x05;
backHistory.push(b1);
backHistory.push(b2);
backHistory.push(b3);
backHistory.push(b4);
backHistory.push(b5);
// backHistory.show();
// System.out.println("大小:"+backHistory.size());
//遍历
byte[] item=null;
while(null!=(item=backHistory.pop())){
System.out.println(item[3]);
}
}
interface Request{
//存款
void deposit();
}
public static void main(String[] args) {
// 模拟 银行存款 业务队列
// ArrayDeque 容器,队列,先进先出
Queue<Request> que =new ArrayDeque<Request>();
//模拟排队情况
for(int i=0;i<10;i++){
final int num =i;
que.offer(new Request(){
@Override
public void deposit() {
System.out.println("第"+num+"个人,办理存款业务,存款额度为:"+(Math.random()*10000));
}
});
}
Request req =null;
while(null!=(req=que.poll())){
req.deposit();
}
}
}