Java SE入门及基础(51) Queue 接口 比较器接口

目录

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 ); // 向队列中添加一个元素,如果出现异常,则返回 false
E remove (); // 移除队列中第一个元素,如果队列中没有元素,则将抛出异常
E poll (); // 移除队列中第一个元素,如果队列中没有元素,则返回 null
E 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 (); // 获取队列中的第一个元素,如果队列为空,则返回null
                System . 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-vip2
        public User ( String name , int level ) {
                this . name = name ;
                this . level = level ;
        }
        @Override
        public String toString () {
                return "User{" +
                        "name='" + name + '\'' +
                        ", level=" + level +
                        '}' ;
        }
        @Override
        public 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 ;
        }
        @Override
        public String toString () {
                return "Student{" +
                        "name='" + name + '\'' +
                        ", age=" + age +
                        '}' ;
        }
        @Override
        public 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 ;
        }
        @Override
        public 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 ) return
                        o1 . 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 接口是外部提供的对两个对象的比较方式的实现,对象本身并没有比 较的方式,因此被称为外排序器

Java SE文章参考:Java SE入门及基础知识合集-CSDN博客

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/bicheng/12844.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【设计模式】JAVA Design Patterns——Abstract Factory(抽象工厂模式)

&#x1f50d;目的 提供一个用于创建相关对象家族的接口&#xff0c;而无需指定其具体类 &#x1f50d;解释 真实世界例子 要创建一个王国&#xff0c;我们需要具有共同主题的对象。精灵王国需要精灵国王、精灵城堡和精灵军队&#xff0c;而兽人王国需要兽人国王、兽人城堡和兽…

项目路由分模块A模块B模块C......模块N使用

路由分模块原因&#xff1a; vue框架中会有router文件&#xff0c;但是路由文件下只有一个路由文件&#xff0c;在实际项目开发中会有多人负责多模块的情况&#xff0c;若都在一个文件内编辑路由名称&#xff0c;就相当于是机房里的数据线&#xff0c;会很乱七八糟&#xff0c;…

1. go语言初识(一)

本篇博客涉及到的内容&#xff1a;变量和常量、iota常量生成器、类型转换 变量&#xff08;Variables&#xff09;和常量&#xff08;Constants&#xff09; 变量&#xff08;Variables&#xff09; 1. 定义变量 在Go中&#xff0c;可以使用’var‘关键字来声明一个变量&…

【十大排序算法】----选择排序(详细图解分析+实现,小白一看就会)

目录 一&#xff1a;选择排序——原理 二&#xff1a;选择排序——分析 三&#xff1a;选择排序——实现 四&#xff1a;选择排序——优化 五&#xff1a;选择排序——效率 一&#xff1a;选择排序——原理 选择排序的原理&#xff1a;通过遍历数组&#xff0c;选出该数组…

使用Docker配置深度学习环境——以diffusers为例

Docker的其他信息可以在我的网站上找到&#xff0c;这里假设安装完成了&#xff0c;直接上手。 git clone 仓库地址打开docker目录&#xff0c;找到目标版本&#xff1a; sudo docker build diffusers-pytorch-cuda如果失败&#xff0c;尝试使用换源&#xff1a; sudo nano …

GPT-4o 炸裂发布!你竟然还没用上?(附详细教程)

今天AI界的爆炸新闻非chatgpt-4o莫属&#xff0c;从早上到现在随处可见的文章推送&#xff0c;视频推送。 大家或多或少都有耳闻了&#xff0c;今天主要讲一讲我们普通人到底怎么用&#xff1f;如果不氪金行不行&#xff1f;我就想体验一下可不可以&#xff1f;带着问题往下看 …

提升写作效率的秘密武器:一个资深编辑的AI写作体验

有句话说:“写作是一项你坐在打字机前流血的工作。”而如今,各类生成式软件的涌现似乎打破了写作这一古老的艺术形式壁垒。过去,作家们独自在书桌前冥思苦想,如今,一款名为“玲珑AI工具”的ai写作助手正悄然改变着文案写作行业的创作生态,成为提升写作效率的秘密武器。 在传统…

【数据结构】图和基本算法

文章目录 1. 图的基本概念1.1 图本身的定义1.2 相关概念 2. 图的存储结构2.1 邻接矩阵2.2 邻接表 3. 图的遍历3.1 广度优先遍历&#xff08;BFS&#xff09;3.2 深度优先遍历&#xff08;DFS&#xff09; 4. 最小生成树4.1 Kruskal算法4.2 Prim算法 5. 最短路径5.1 单源最短路径…

【Linux】基础命令:进程、网络

systemctl命令 控制内置服务 systemctl start | stop | status | enable | disable 服务名 start | stop开启关闭&#xff0c;status状态&#xff0c;enable | disable开启关闭开机自启 date命令 查看系统时间 date [-d] [格式化字符串] date -d “1 day” %Y-%m-%d 修改时区…

表达式运算符位运算

表达式 概念&#xff1a; 由常量、变量、运算符、&#xff08;&#xff09;组成一句代码。代码最终有一个结果。 // 定义&#xff1a; 由常量、变量、运算符、&#xff08;&#xff09;组成。由一个结果// 规律1&#xff1a; 当表达式中所有的变量类型小于等于int( int shor…

Linux0.11 中全局描述符表(GDT)

在Linux内核中&#xff0c;全局描述符表&#xff08;Global Descriptor Table&#xff0c;简称GDT&#xff09;是一个关键的数据结构&#xff0c;主要用于管理处理器的内存段和相关的权限与属性。它属于x86架构中的保护模式特性&#xff0c;允许操作系统对内存访问进行更精细的…

深度学习技术之卷积神经网络

深度学习技术 卷积神经网络1. 导入需要的库2. 加载并显示两张图像2.1 加载图像2.2 创建子图2.3 打印图像形状2.4 打印合并后的图像数组的形状 3. 卷积层3.1 定义变量3.1.1 卷积核的大小&#xff08;u&#xff09;3.1.2 滑动步长&#xff08;s&#xff09;3.1.3 输出特征图的数量…

你了解 pom.xml 吗

你了解pomxml吗 springboot 是 java 利器&#xff0c;几乎每个写 java 的同学都会用&#xff0c;但是你了解 pom.xml 吗&#xff1f; 这篇干货查漏补缺。 首先我们创建个 springboot 项目 都选了默认设置&#xff1a; 我把这篇完整粘贴出来 pom.xml <?xml version&quo…

键盘控制小蛇移动

/*** Description 键盘控制小蛇移动*/ package com.ai.snake;import javax.swing.*;public class StartGame {public static void main(String[] args) {JFrame frame new JFrame();frame.setBounds(10,10,900,720);frame.setResizable(false); //窗口大小不可变frame.setDef…

Termius mac:一站式跨平台终端工具

Termius mac 8.4是一款远程访问和管理工具&#xff0c;旨在帮助用户轻松地远程连接到各种服务器和设备。它适用于多种操作系统&#xff0c;包括Windows、macOS、Linux和移动设备。 该软件提供了一个直观的界面&#xff0c;使用户可以通过SSH、Telnet和Mosh等协议连接到远程设备…

Linux 通过关键字查找文件

按文件名查找 find 路径 -name “文件名” 查找当前目录下的所有mk文件 find . -name "*.mk"按关键字查找 find 路径 -name “文件名” | xargs grep -n “关键字” 参数&#xff1a; xargs 是给命令传递参数的一个过滤器&#xff0c;也是组合多个命令的一个工具 -n…

【挑战全网】最全高德地图充电桩接入指南,流量必火!

分享《一套免费开源充电桩物联网系统&#xff0c;是可以立马拿去商用的&#xff01;》 一、和高德直接互联互通的优势&#xff1a; 1、高德官方直接互联互通&#xff0c;提供给合作商户独立发展自主权&#xff0c;不依赖任何第三方平台; 2、自己控制电站的上线、下线、修改电…

Redis教程(八):Redis中zSet类型的常用命令

zSet操作&#xff1a; 往zSet有序集合中添加数据&#xff0c;1&#xff0c;2&#xff0c;3代表权重&#xff0c;one&#xff0c;two&#xff0c;three代表数据 zadd myzset 1 one 2 two 3 three 查询zSet中所有的值&#xff0c;第一个参数为0代表从小到大排序&#xff0c;为…

MemoryModule - 应用编程细节

文章目录 MemoryModule - 应用编程细节概述笔记实验环境升级MemoryModule&#xff0c;在上下文中加入DLL在内存载入前的信息MemoryModule.hMemoryModule.cpp实现接口MemoryGetPayload() 整理 - 在内存载入的DLL中&#xff0c;取得资源表中的信息&#xff0c;取得载入前的DLL内容…

从0开始理解云原生架构

一、云原生发展历史 云原生概念最早起源于2013年&#xff0c;由 Matt Stine 首次提出“Cloud Native”这一术语&#xff0c;这个概念强调了应用需要充分利用云的优势&#xff0c;如弹性、可扩展性和服务化。2015年&#xff0c;Matt Stine出版了《迁移到云原生架构》一书&am…