给jdk写注释系列之jdk1.6容器(9)-Strategy设计模式之Comparable&Comparator接口
public class DataSort { public static void sort( int[] arr) {
for (int i = arr.length; i > 0; i--) {
for (int j = 0; j < i - 1; j++) {
// 如果前一个比后一个大,那么就把大值交换到后面去
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
测试类:
public class Test { public static void main(String[] args) {
int[] arr = new int[] { 9, 5, 2, 7 };
DataSort. sort(arr);
for (int i : arr) {
System. out.print(i + " " );
}
}
}
运行一下看看结果:
2 5 7 9
public class Person { private String name ;
private int age;
private int money; public Person(String name, int age, int money) {
this.name = name;
this.age = age;
this.money = money;
} 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 getMoney() {
return money ;
} public void setMoney(int money) {
this.money = money;
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", money=" + money
+ "]";
} }
Penson这个类定义完成了,怎么进行排序呢,比如你说谁收入高谁老大,ok那么我们就按收入写一下排序方法:
public class DataSort { public static void sort( int[] arr) {
for (int i = arr.length; i > 0; i--) {
for (int j = 0; j < i - 1; j++) {
// 如果前一个比后一个大,那么就把大值交换到后面去
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
} public static void sort(Person[] arr) {
for (int i = arr.length; i > 0; i--) {
for (int j = 0; j < i - 1; j++) {
// 如果前一个比后一个大,那么就把大值交换到后面去
if (arr[j].getMoney() > arr[j + 1].getMoney()) {
Person temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
我们在DataSort中重写了一个sort(Person[] arr)方法,用来给Person类进行排序,测试一下吧:
public class Test { public static void main(String[] args) {
// int[] arr = new int[] { 9, 5, 2, 7 };
// DataSort.sort(arr);
// for (int i : arr) {
// System.out.print(i + " ");
// } Person p1 = new Person("张三" , 25, 100); // 张三,25岁,年薪100w
Person p2 = new Person("李四" , 30, 10); // 李四,30岁,年薪10w
Person p3 = new Person("王五" , 20, 1000); // 王五,25岁,年薪1000w
Person[] arr = new Person[] { p1, p2, p3 }; DataSort. sort(arr);
for (Person p : arr) {
System. out.println(p + " " );
}
}
}
看下结果:
Person [name=李四, age=30, money=10]
Person [name=张三, age=25, money=100]
Person [name=王五, age=20, money=1000]
public interface MyComparable { /**
* 返回值大于0说明当前比较的Object大,小于0说明被比较的Object大,
* 等于0说明两个Object相等
*/
public int compareTo(Object o);
}
public class DataSort { public static void sort(MyComparable[] arr) {
for (int i = arr.length; i > 0; i--) {
for (int j = 0; j < i - 1; j++) {
if (arr[j].compareTo(arr[j + 1]) > 0) {
MyComparable temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
} }
是不是很简单了,只要用compareTo的返回结果就可以了,下面我们让Person实现MyComparable接口试一下:
public class Person implements MyComparable { private String name ;
private int age;
private int money; public Person(String name, int age, int money) {
this.name = name;
this.age = age;
this.money = money;
} 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 getMoney() {
return money ;
} public void setMoney(int money) {
this.money = money;
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", money=" + money
+ "]";
} @Override
public int compareTo(Object o) {
Person p = (Person)o;
if (this.money > p. money) {
return 1;
} else {
return -1;
}
} }
测试一下:
public class Test { public static void main(String[] args) {
// int[] arr = new int[] { 9, 5, 2, 7 };
// DataSort.sort(arr);
// for (int i : arr) {
// System.out.print(i + " ");
// } Person p1 = new Person("张三" , 25, 100); // 张三,25岁,年薪100w
Person p2 = new Person("李四" , 30, 10); // 李四,30岁,年薪10w
Person p3 = new Person("王五" , 20, 1000); // 王五,25岁,年薪1000w
Person[] arr = new Person[] { p1, p2, p3 }; DataSort. sort(arr);
for (Person p : arr) {
System. out.println(p + " " );
}
}
}
看一下结果:
Person [name=李四, age=30, money=10]
Person [name=张三, age=25, money=100]
Person [name=王五, age=20, money=1000]
public interface MyComparator {
public int compare(Object o1, Object o2);
}
注意,这个接口不是让你的排序类来实现的,看看我sort怎么写:
public class DataSort { public static void sort(MyComparable[] arr) {
for (int i = arr.length; i > 0; i--) {
for (int j = 0; j < i - 1; j++) {
if (arr[j].compareTo(arr[j + 1]) > 0) {
MyComparable temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
} public static void sort(Object[] arr, MyComparator c) {
for (int i = arr.length; i > 0; i--) {
for (int j = 0; j < i - 1; j++) {
if (c.compare(arr[j], arr[j + 1]) > 0) {
Object temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
} }
public class PersonAgeComparator implements MyComparator { @Override
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2; if (p1.getAge() - p2.getAge() > 0) {
return 1;
} else {
return -1;
}
} }
具体看看怎么来用:
public class Test { public static void main(String[] args) {
// int[] arr = new int[] { 9, 5, 2, 7 };
// DataSort.sort(arr);
// for (int i : arr) {
// System.out.print(i + " ");
// } Person p1 = new Person("张三" , 25, 100); // 张三,25岁,年薪100w
Person p2 = new Person("李四" , 30, 10); // 李四,30岁,年薪10w
Person p3 = new Person("王五" , 20, 1000); // 王五,25岁,年薪1000w
Person[] arr = new Person[] { p1, p2, p3 }; DataSort. sort(arr, new PersonAgeComparator());
for (Person p : arr) {
System. out.println(p + " " );
}
}
}
我只需要把我的比较大小逻辑类传入sort就可以了,看下结果:
Person [name=王五, age=20, money=1000]
Person [name=张三, age=25, money=100]
Person [name=李四, age=30, money=10]
public class Person implements MyComparable { private String name ;
private int age;
private int money; private MyComparator comparator = new PersonAgeComparator(); public Person(String name, int age, int money) {
this.name = name;
this.age = age;
this.money = money;
} public Person(String name, int age, int money, MyComparator comparator) {
this.name = name;
this.age = age;
this.money = money;
this.comparator = comparator;
} 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 getMoney() {
return money ;
} public void setMoney(int money) {
this.money = money;
} @Override
public String toString() {
return "Person [name=" + name + ", age=" + age + ", money=" + money
+ "]";
} @Override
public int compareTo(Object o) {
return comparator .compare(this, o);
} }
public V put(K key, V value) {
......
...... // split comparator and comparable paths
// 当前使用的比较器
Comparator<? super K> cpr = comparator ;
// 如果比较器不为空,就是用指定的比较器来维护TreeMap的元素顺序
if (cpr != null) {
// do while循环,查找key要插入的位置(也就是新节点的父节点是谁)
do {
// 记录上次循环的节点t
parent = t;
// 比较当前节点的key和新插入的key的大小
cmp = cpr.compare(key, t. key);
// 新插入的key小的话,则以当前节点的左孩子节点为新的比较节点
if (cmp < 0)
t = t. left;
// 新插入的key大的话,则以当前节点的右孩子节点为新的比较节点
else if (cmp > 0)
t = t. right;
else
// 如果当前节点的key和新插入的key想的的话,则覆盖map的value,返回
return t.setValue(value);
// 只有当t为null,也就是没有要比较节点的时候,代表已经找到新节点要插入的位置
} while (t != null);
}
else {
// 如果比较器为空,则使用key作为比较器进行比较
// 这里要求key不能为空,并且必须实现Comparable接口
if (key == null)
throw new NullPointerException();
Comparable<? super K> k = (Comparable<? super K>) key;
// 和上面一样,喜欢查找新节点要插入的位置
do {
parent = t;
cmp = k.compareTo(t. key);
if (cmp < 0)
t = t. left;
else if (cmp > 0)
t = t. right;
else
return t.setValue(value);
} while (t != null);
} ......
......
}
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
public interface Comparable<T> {
public int compareTo(T o);
}
唯一不同的是Comparator接口中要求重写equals方法,用于比较是否相等。
给jdk写注释系列之jdk1.6容器(9)-Strategy设计模式之Comparable&Comparator接口的更多相关文章
- 给jdk写注释系列之jdk1.6容器(12)-PriorityQueue源码解析
PriorityQueue是一种什么样的容器呢?看过前面的几个jdk容器分析的话,看到Queue这个单词你一定会,哦~这是一种队列.是的,PriorityQueue是一种队列,但是它又是一种什么样的队 ...
- 给jdk写注释系列之jdk1.6容器(3)-Iterator设计模式
前面讲了两种List,一种基于数组实现的ArrayList,一种基于链表实现的LinkedList,这两种list是我们工作中最常用到的List容器.当然数组和链表也是两种常见的基本数据结构,其他基本 ...
- 给jdk写注释系列之jdk1.6容器(6)-HashSet源码解析&Map迭代器
今天的主角是HashSet,Set是什么东东,当然也是一种java容器了. 现在再看到Hash心底里有没有会心一笑呢,这里不再赘述hash的概念原理等一大堆东西了(不懂得需要先回去看下Has ...
- 给jdk写注释系列之jdk1.6容器(2)-LinkedList源码解析
LinkedList是基于链表结构的一种List,在分析LinkedList源码前有必要对链表结构进行说明. 1.链表的概念 链表是由一系列非连续的节点组成的存储结构,简单分下类的话,链 ...
- 给jdk写注释系列之jdk1.6容器(1)-ArrayList源码解析
工作中经常听到别人讲“容器”,各种各样的容器,话说到底什么是容器,通俗的讲“容器就是用来装东西的器皿,比如:水桶就是用来盛水的,水桶就是一个容器.” ok,在我们写程序的时候常常要对大量的对象进行管理 ...
- 给jdk写注释系列之jdk1.6容器(13)-总结篇之Java集合与数据结构
是的,这篇blogs是一个总结篇,最开始的时候我提到过,对于java容器或集合的学习也可以看做是对数据结构的学习与应用.在前面我们分析了很多的java容器,也接触了好多种常用的数据结构,今天 ...
- 给jdk写注释系列之jdk1.6容器(11)-Queue之ArrayDeque源码解析
前面讲了Stack是一种先进后出的数据结构:栈,那么对应的Queue是一种先进先出(First In First Out)的数据结构:队列. 对比一下Stack,Queue是一种先进先出的容 ...
- 给jdk写注释系列之jdk1.6容器(10)-Stack&Vector源码解析
前面我们已经接触过几种数据结构了,有数组.链表.Hash表.红黑树(二叉查询树),今天再来看另外一种数据结构:栈. 什么是栈呢,我就不找它具体的定义了,直接举个例子,栈就相当于一个很窄的木桶 ...
- 给jdk写注释系列之jdk1.6容器(8)-TreeSet&NavigableMap&NavigableSet源码解析
TreeSet是一个有序的Set集合. 既然是有序,那么它是靠什么来维持顺序的呢,回忆一下TreeMap中是怎么比较两个key大小的,是通过一个比较器Comparator对不对,不过遗憾的是,今天仍然 ...
随机推荐
- 如何使用git创建远程仓库(供局域网多人使用)
用git init(默认创建的是私人的仓库)创建的仓库,推送是不会成功的. 因此在git server端,我们要用 git --bare init --shared=group 来创建一个bare库, ...
- 转载-MySQL 加锁处理分析
MySQL 加锁处理分析 发表于 2013 年 12 月 13 日 由 hedengcheng 1 背景 1 1.1 MVCC:Snapshot Read vs Current Re ...
- ORM 是一种讨厌的反模式
本文由码农网 – 孙腾浩原创翻译,转载请看清文末的转载要求,欢迎参与我们的付费投稿计划! (“Too Long; Didn’t Read.”太长不想看,可以看这段摘要 )ORM是一种讨厌的反模式,违背 ...
- [iOS 多线程 & 网络 - 4.0] - AFN框架简单使用
A.AFN基本知识 1.概念 AFNetworking 是对NSURLConnection的封装 运行效率没有ASI高(因为ASI基于CFNetwork),但是使用简单 AFN支持ARC B. ...
- CodeForces 705A Hulk (水题)
题意:输入一个 n,让你输出一行字符串. 析:很水题,只要判定奇偶性,输出就好. 代码如下: #pragma comment(linker, "/STACK:1024000000,10240 ...
- presentedViewController 和 presentingViewController 以及 dismissViewControllerAnimated 的使用
在日常的开发中,多控制器之间的跳转除了使用push的方式,还可以使用 present的方式,present控制器时,就避免不了使用 presentedViewController.presenting ...
- Castle ActiveRecord学习实践
Castle是针对.NET平台的一个开源项目,从数据访问框架ORM到IOC容器,再到WEB层的MVC框架.AOP,基本包括了整个开发过程中的所有东西,为我们快速的构建企业级的应用程序提供了很好的服务. ...
- The plot Function in matlab
from http://pundit.pratt.duke.edu/wiki/MATLAB:Plotting The plot Function The plot function is used t ...
- DX相机变换矩阵推导
网上很多的推导过程都是错的,所以写一个. 先平移,再旋转就可以,先平移的原因是,如果先旋转的话,坐标系已经改了,所以先平移. 平移的变换和相机的变换是相反的,所以是: 平移完成后,相机的位置就和原点的 ...
- Codeforces Round #274 (Div. 1) B. Long Jumps 数学
B. Long Jumps Time Limit: 1 Sec Memory Limit: 256 MB 题目连接 http://codeforces.com/contest/480/problem/ ...