目录
Queue 接口
1. 特性描述
Queue 接口常用方法
2. LinkedBlockingQueue
用法示例
3. PriorityQueue
用法示例
思考:如果 PriorityQueue 队列中存储的是对象,会怎么排序?
比较器接口
1. 比较器接口的作用
2. Comparable 接口
示例
3. Comparator 接口
示例
Java SE文章参考:Java SE入门及基础知识合集-CSDN博客
Queue 接口
1. 特性描述
A Queue is a collection for holding elements prior to processing. Besides basic Collection operations, queues provide additional insertion, removal, and inspection operations.队列是用于在处理之前保存元素的集合。 除了基本的收集操作外,队列还提供其他插入,移除和检查操作。Queues typically, but not necessarily, order elements in a FIFO (first-in first-out) manner. Among the exceptions are priority queues, which order elements according to their values — see the Object Ordering section for details). Whatever ordering is used, the head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue. Other kinds of queues may use different placement rules. Every Queue implementation must specify its ordering properties.队列通常但不是必须以FIFO (先进先出)的方式对元素进行排序。 优先队列除外,它们根据元素的值对元素进行排序(有关详细信息,请参见“ 对象排序 ” 部分)。 无论使用哪种排序,队列的开头都是将通过调用remove 或 poll 删除的元素。 在 FIFO 队列中,所有新元素都插入到队列的尾部。 其他种类的队列可能使用不同的放置规则。 每个Queue 实现必须指定其排序属性。It is possible for a Queue implementation to restrict the number of elements that it holds; such queues are known as bounded. Some Queue implementations in java.util.concurrent are bounded, but the implementations in java.util are not.队列实现有可能限制其持有的元素数量; 这样的队列称为有界队列java.util.concurrent 中的某些Queue 实现是有界的,但 java.util 中的某些实现不受限制。
Queue 接口常用方法
boolean add ( E e ); // 向队列中添加一个元素,如果出现异常,则直接抛出异常boolean offer ( E e ); // 向队列中添加一个元素,如果出现异常,则返回 falseE remove (); // 移除队列中第一个元素,如果队列中没有元素,则将抛出异常E poll (); // 移除队列中第一个元素,如果队列中没有元素,则返回 nullE element (); // 获取队列中的第一个元素,但不会移除。如果队列为空,则将抛出异常E peek (); // 获取队列中的第一个元素,但不会移除。如果队列为空,则返回 null
2. LinkedBlockingQueue
LinkedBlockingQueue 是一个 FIFO 队列,队列有长度,超出长度范围的元素将无法存储进队列。
用法示例
import java . util . concurrent . LinkedBlockingQueue ;public class LinkedBlockingQueueTest {public static void main ( String [] args ) {//构建队列时,我们通常都会给队列设置一个容量,因为默认容量太大了LinkedBlockingQueue < String > queue = new LinkedBlockingQueue <> ( 5 );// String first = queue.element();//获取队列中的第一个元素,如果队列为空, 则抛出异常// System.out.println(first);String first = queue . peek (); // 获取队列中的第一个元素,如果队列为空,则返回nullSystem . out . println ( first );queue . add ( "a" );queue . add ( "b" );queue . add ( "c" );queue . add ( "d" );queue . add ( "e" );// queue.add("f");//放入第6 个元素将抛出异常boolean success = queue . offer ( "f" ); // 放入第 6 个元素不会抛出异常,只会返回false,表明放入失败System . out . println ( success );queue . remove ();queue . remove ();queue . remove ();queue . remove ();queue . remove ();System . out . println ( "================" );// queue.remove();//移除第6 个元素将抛出异常while ( ! queue . isEmpty ()){String s = queue . poll ();System . out . println ( s );}String s = queue . poll (); // 移除第 6 个元素不会抛出异常,但会返回 null 值System . out . println ( s );}}
3. PriorityQueue
PriorityQueue 是一个有排序规则的队列,存入进去的元素是无序的,队列有长度,超出长度范围的元素将无法存储进队列。需要注意的是, 如果存储的元素如果不能进行比较排序,也未提供任何对元素 进行排序的方式,运行时会抛出异常
用法示例
import java . util . PriorityQueue ;public class PriorityQueueTest {public static void main ( String [] args ) {PriorityQueue < Integer > queue = new PriorityQueue <> ();queue . offer ( 1 );queue . offer ( 4 );queue . offer ( 3 );queue . offer ( 5 );queue . offer ( 2 );for ( Integer number : queue ){System . out . println ( number );}System . out . println ( "================" );while ( ! queue . isEmpty ()){Integer number = queue . poll ();System . out . println ( number );}}}
思考:如果 PriorityQueue 队列中存储的是对象,会怎么排序?
import java . util . PriorityQueue ;public class PriorityQueueTest {public static void main ( String [] args ) {PriorityQueue < Integer > queue = new PriorityQueue <> ();queue . offer ( 1 );queue . offer ( 4 );queue . offer ( 3 );queue . offer ( 5 );queue . offer ( 2 );for ( Integer number : queue ){System . out . println ( number );}System . out . println ( "================" );while ( ! queue . isEmpty ()){Integer number = queue . poll ();System . out . println ( number );}PriorityQueue < User > userQueue = new PriorityQueue <> ();userQueue . offer ( new User ( " 张三 " , 0 ));userQueue . offer ( new User ( " 李四 " , 1 ));userQueue . offer ( new User ( " 金凤 " , 3 ));userQueue . offer ( new User ( " 龙华 " , 2 ));}}
如果对象不能进行比较,则不能排序,运行时会报异常。要解决这个问题,需要使用Java 平台提供的比较器接口。
比较器接口
1. 比较器接口的作用
在使用数组或者集合时,我们经常都会遇到排序问题,比如将学生信息按照学生的成绩从高到低依次排列。数字能够直接比较大小,对象不能够直接比较大小,为了解决这个问题,Java 平台提供了 Comparable 和 Comparator 两个接口来解决。
2. Comparable 接口
This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.接口对实现该接口的每个类的对象强加了总体排序。 此排序称为类的自然排序,而该类的compareTo 方法被称为其自然比较方法
示例
public class User implements Comparable < User > {private String name ;private int level ; // 等级 0- 普通用户 1-vip1 2-vip2public User ( String name , int level ) {this . name = name ;this . level = level ;}@Overridepublic String toString () {return "User{" +"name='" + name + '\'' +", level=" + level +'}' ;}@Overridepublic int compareTo ( User o ) {if ( level == o . level ) return 0 ;else if ( level < o . level ) return - 1 ;else return 1 ;}}package com . wq . queue ;import java . util . PriorityQueue ;public class PriorityQueueTest {public static void main ( String [] args ) {PriorityQueue < Integer > queue = new PriorityQueue <> ();queue . offer ( 1 );queue . offer ( 4 );queue . offer ( 3 );queue . offer ( 5 );queue . offer ( 2 );for ( Integer number : queue ){System . out . println ( number );}System . out . println ( "================" );while ( ! queue . isEmpty ()){Integer number = queue . poll ();System . out . println ( number );}PriorityQueue < User > userQueue = new PriorityQueue <> ();userQueue . offer ( new User ( " 张三 " , 0 ));userQueue . offer ( new User ( " 李四 " , 1 ));userQueue . offer ( new User ( " 金凤 " , 3 ));userQueue . offer ( new User ( " 龙华 " , 2 ));while ( ! userQueue . isEmpty ()){User user = userQueue . poll ();System . out . println ( user );}}}
package com . wq . compare ;public class Student implements Comparable < Student > {private String name ;private int age ;public Student ( String name , int age ) {this . name = name ;this . age = age ;}@Overridepublic String toString () {return "Student{" +"name='" + name + '\'' +", age=" + age +'}' ;}@Overridepublic int compareTo ( Student o ) {if ( age == o . age ) return name . compareTo ( o . name );else if ( age < o . age ) return 1 ;else return - 1 ;}}package com . wq . compare ;import java . util . ArrayList ;import java . util . Arrays ;import java . util . Collections ;import java . util . List ;public class ComparableTest {public static void main ( String [] args ) {Student [] students = {new Student ( " 张三 " , 25 ),new Student ( " 李四 " , 21 ),new Student ( " 王五 " , 23 ),new Student ( " 龙华 " , 28 )};Arrays . sort ( students );for ( Student s : students ){System . out . println ( s );}System . out . println ( "===================" );List < Student > studentList = new ArrayList <> ();studentList . add ( new Student ( " 张三 " , 25 ));studentList . add ( new Student ( " 李四 " , 21 ));studentList . add ( new Student ( " 王五 " , 23 ));studentList . add ( new Student ( " 龙华 " , 28 ));//对集合排序Collections . sort ( studentList );for ( Student s : studentList ){System . out . println ( s );}System . out . println ( "==========================" );String [] strings = { "d" , "b" , "a" , "c" };Arrays . sort ( strings );for ( String str : strings ){System . out . println ( str );}}}
3. Comparator 接口
A comparison function, which imposes a total ordering on some collection of objects. Comparators can be passed to a sort method (such as Collections.sort or Arrays.sort) to allow precise control over the sort order.比较功能,对某些对象集合施加总排序。 可以将比较器传递给排序方法(例如Collections.sort 或Arrays.sort),以实现对排序顺序的精确控制。
示例
package com . wq . compare ;public class Course {private String name ;private int score ;public Course ( String name , int score ) {this . name = name ;this . score = score ;}public String getName () {return name ;}public int getScore () {return score ;}@Overridepublic String toString () {return "Course{" +"name='" + name + '\'' +", score=" + score +'}' ;}}package com . wq . compare ;import java . util . * ;public class ComparatorTest {public static void main ( String [] args ) {Course [] courses = {new Course ( "Java" , 5 ),new Course ( "Html" , 3 ),new Course ( "JavaScript" , 2 ),new Course ( "JDBC" , 6 )};// Comparator<Course> c = new Comparator<Course>() {// @Override// public int compare(Course o1, Course o2) {// return 0;// }// };// Comparator<Course> c = (Course o1, Course o2) -> {// return 0;// };Comparator < Course > c = ( o1 , o2 ) -> {int score1 = o1 . getScore ();int score2 = o2 . getScore ();if ( score1 == score2 ) returno1 . getName (). compareTo ( o2 . getName ());else if ( score1 < score2 ) return - 1 ;else return 1 ;};Arrays . sort ( courses , c );for ( Course course : courses ){System . out . println ( course );}System . out . println ( "=================" );List < Course > courseList = new ArrayList <> ();courseList . add ( new Course ( "Java" , 5 ));courseList . add ( new Course ( "Html" , 3 ));courseList . add ( new Course ( "JavaScript" , 2 ));courseList . add ( new Course ( "JDBC" , 6 ));Collections . sort ( courseList , c );for ( Course course : courseList ){System . out . println ( course );}}}
Comparable接口是有数组或者集合中的对象的类所实现,实现后对象就拥有比较的方法,因此称为内 排序或者自然排序。 Comparator 接口是外部提供的对两个对象的比较方式的实现,对象本身并没有比 较的方式,因此被称为外排序器