浅析 Comparable 和 Comparator

Winform从入门到精通(1)——Label(史上最全) 本篇文章是对专栏《winform控件从入门到精通》的详细介绍 阅读详情

相同点

  • 都是用来实现集合中元素的比较从而进行排序。
  • compare(T o1, T o2) 和 o1.compareTo(o2) 类似,定义排序规则后返回正数,零和负数分别代表大于,等于和小于。
  • 一个类要实现排序功能既可以通过内部实现 Comparable 接口也可以通过外部实现 Comparator 接口。

不同点

  • 接口定义位置不同:
    • java.lang.Comparable
    • java.util.Comparator。
  • 接口中定义方法不同:
    • Comparable 中定义 public int compareTo(T o)。
    • Comparator 中定义 public int compare(T o1, T o2)。
  • 实现排序方式不同:
    • Comparable 相对于内部比较器:通过类实现 Comparable 接口然后在类中重写 compareTo 方法实现排序功能。
    • Comparator 相对于外部比较器:在类外定义 Comparator 接口然后重写 compare 方法用于类比较进而实现排序功能。
  • 侧重点不同:
    • Comparable 一般用于类的自然序,即默认的排序方式。比如学生默认以学号排序。
    • Comparator 则用于定制化排序,即拓展的排序方式。比如学生按照年龄排序。或者为没有实现 Comparable,即没有默认排序方式的类在不改变类自身结构的情况下提供一种比较方式。

示例

示例代码

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[0] = new Student("lucy",21);
        students[1] = new Student("tom",23);
        students[2] = new Student("anna",25);
        // 使用默认的排序方式:以姓名排序
        // 由于实现了Comparable接口,所以可以直接使用Arrays.sort排序
        // Arrays.sort使用Comparable实现的内部比较器
        Arrays.sort(students);
        System.out.println("使用Comparable排序");
        for (Student student : students) {
            System.out.println(student);
        }

        System.out.println("===========================");
        // 使用扩展的排序方式:以年龄升序排序
        // 为Arrays.sort传入一个外部实现的Comparator比较器
        Arrays.sort(students, new Comparator<Student>() {
            @Override
            public int compare(Student s1, Student s2) {
                return Integer.compare(s1.age, s2.age);
            }
        });

        System.out.println("使用Comparator排序");
        for (Student student : students) {
            System.out.println(student);
        }
    }
}

class Student implements Comparable<Student> {
    public String name;
    public int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int compareTo(Student o) {
        return this.name.compareTo(o.name);
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

示例结果

在这里插入图片描述

Python 爬虫实战:京东商品价格与评论数据爬取 本文介绍了使用Python爬取京东商品价格与评论数据的完整流程。主要内容包括: 环境准备:安装requests、BeautifulSoup、pandas等库,建议使用Python 3.8+虚拟环境。 目标分析: 商品列表页(HTML)包含名称、价格、SKU ID等数据 评论数据通过JSON API获取 反爬策略: 随机User-Agent 请求延迟2-5秒 设置必要Cookie 代码实现: 基础配置:设置输出目录、随机UA生成器 搜索列表页爬取:解析HTML获取商品基本信息 评论数据爬取:通过JSON AP 阅读详情

相关推荐

基于车辆运动学的规划算法 - Hybrid A*/ State Lattice Planning (前置知识:自行车模型、Dubins、Reeds Shepp、多项式曲线、螺旋曲线)

本文将按顺序讲解基于车辆运动学的规划算法,以及需要的前置知识:自行车模型、Dubins和Reeds Shepp曲线、多项式曲线和螺旋曲线

BigDavid123的博客 4859

Java Comparator接口和compareto方法总结

compare(Object o1,Object o2)方法是java.util.Comparator接口的方法,它实际上用的是待比较对象的compareTo(Object o)方法。 之前一直搞不清楚自定义的compare的返回值到底怎么处理,一番查询和总结后得到如下结果: compare(Object o1,Object o2)方法中,默认采用的是o1-o2,若o1<o2,返回值为-1;若o1==o2,返回值为0;若o1>o2,返回值为1;而其排序结果是按-1来排序的,即默认为从小到大排序。

GOV_D的博客 2026

相机图像质量研究(15)常见问题总结:光学结构对成像的影响--暗角

老式相机的暗角往往比较明显,周围一圈能够明显感觉到亮度下降的很多,当然有些电源模仿手持相机的摄影效果,也能看到周围明显的亮度下降。一、

xiaoshixiu的专栏 1123

Java用CompareTo方法实现根据两个或多个属性对对象进行排序

CompareTo方法 CompareTo是String类的方法,CompareTo(Object o1,Object o2),就是用o1和o2进行比较 o1.compateTo(o2) 大于0 则o1大 o1.compateTo(o2) 小于0 则o2大 o1.compateTo(o2) 等于0 则一样大 升序降序 升序: public static void main(String...

bernardGao94的博客 1837

C++总结笔记

/ ++操作 这是因为定义的数组,申请的是连续的内存空间,当ptr++(ptr是int类型的指针变量),地址空间向后偏移是以int类型的大小为单位进行偏移的,相当于int类型数组元素的向后偏移。使用场景:它是最通用的转换形式,用于将一种类型转换为另一种类型,例如基本数据类型的转换(如 float 转 int),指向基类的指针或引用转为指向派生类的指针或引用等。在派生类被调用时会调用派生类中的函数,不会调用基类中的被重写的函数(基类中的函数需要加上virtual才可以,即基类中的函数是虚函数)。

weixin_50890461的博客 5233

24届-Python面经(华为OD)

【摘要】24届非科班生通过栗栗姐指导成功转行华为OD。从4月4日零基础准备,经历机考(4/18)、测评(4/19)、资格面(5/7)、技术面(5/9-11)到5月17日获offer。全程栗栗姐提供题库、面经指导和实时跟进。虽遇压力面和技术短板,但在专业辅导下10天走完全流程。案例证明转行需自身努力+优质HR支持,栗栗姐团队提供多岗位(Java/Python等)、多地域(北上深等)OD机会,含笔试资料和全流程攻略。

2401_86909848的博客 1188

Java_集合

集合 集合是JavaAPI中提供的一种容器工具,可以用来存储多个数据。 集合和数组之间的区别有: (1)数组的长度是固定的,集合的长度是可变的; (2)数组中存储的是同一类型的元素,集合中存储的数据可以是不同类型的; (3)数组中可以存放基本类型数据或者对象,集合中只能存放对象; (4)数组是由JVM中现有的类型+[]组合而成的,只有一个length属性,还有从Object中继承过来的方法;集合是由JavaAPI中的java.util包里面所提供的接口和实现类组成的,这里面定义并实现了很多方法,可以使用集合

应付就业 ·· 规划职业? 234

Zemax中场曲与畸变图的深度解析与应用场景对比

本文深度解析了Zemax中场曲/畸变图与网格畸变图的核心原理、计算逻辑与适用场景。通过对比常规成像镜头、扫描镜头、鱼眼镜头及变形宽银幕镜头等实际案例,详细阐述了如何根据系统对称性、视场角及核心需求选择正确的分析工具与畸变评价标准,为光学设计中的畸变诊断与优化提供清晰指导。

sand8的博客 482

Java:Java8新特性

1. Lambda表达式 1.1 Lambda表达式的好处 Lambda 是一个匿名函数,我们可以把 Lambda 表达式理解为是一段可以传递的代码(将代码像数据一样进行传递) 使用它可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升 Lambda表达式的本质是:作为函数式接口的实例 1.2 Lambda表达式举例 //导入的包有;import org.junit.Test;import java.util.Comparator; public class Lam.

weixin_44330955的博客 306

基于模型上下文协议(MCP)的可插拔式临床AI工具链Clinical DS研究(下)

本研究深入探讨了医疗AI在临床落地中的核心矛盾,即如何从“模型能答”迈向“系统可信、可用、可追溯”。为解决此矛盾,我们创新性地提出并详细设计实现了一套基于模型上下文协议(MCP)的**“可插拔式临床AI工具链”**架构。通过将复杂的医疗AI系统解构为Host、MCP Server和标准协议三层,并将各类能力(临床决策、影像分析、合规审计)封装为标准的、可独立演进的Server,我们成功地构建了一个模块化、高内聚、低耦合的系统。

AllenLV的博客 1380

Vulkan入门系列0- Vulkan与OpenGL的区别

虽然Vulkan和OpenGL都是对GPU的抽象,都能达到相同的功能,但它们的设计理念不同,可以说设计差异是非常之大,由于OpenGL从1992年到现在,已经有30多年的历史,GPU功能日新月异,与当年不可同日而语,在OpenGL保持向下兼容情况下,还要在OpenGL基础上设计一套编程接口显然是不可能的,所以推出了新编程规范Vulkan。另外在一些无窗口的应用中,Vulkan可以有选择的不创建帧缓冲区,比如在数学运算,物理模拟,处理视频流的应用中并不需要窗口,所以Vulkan支持更灵活的应用场景。

GPU全栈博主 4069

java重写compareTo()方法,比较对象的大小

package com.example.demo; /** * 商品类 */ public class Goods implements Comparable{ private String name; private double price; public Goods() { } public Goods(String name, double price) { this.name = name; this.price.

weixin_45654215的博客 1万+

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

浅析 Comparable和 Comparator的区别

简介 Comparable和 Comparator都是java.util包下的两个接口,从字面上看这两个接口都是用来做比较用的,但是jdk里面不可能定义两个功能相同的接口,所以他们肯定有不同的用处。 1、Comparable 1.1 说明 Comparable可以认为是一个内比较器,实现了Comparable接口的类有一个特点,就是这些 类是可以和自己比较的,至于具体和另一个实现了Compar...

wlh2015的博客 3万+

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Comparable与Comparator浅析

  今天博主在翻阅TreeMap的源码,发现其键必须是实现Comparable或者Comparator的接口时产生了一些兴趣,比如在TreeMap中的put方法分别对Comparable和Comparator接口分别进行处理。那么疑问就来了,Comparable和Comparator接口的区别是什么,Java中为什么会存在两个类似的接口?   Comparable和Comparator接口都是用...

朱小厮的博客 2万+

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

浅析Comparable和Comparator

一.概述 Java 中的排序是由 Comparable 和 Comparator 这两个接口来实现的。 Comparable表示可被排序的,实现该接口的类的对象自动拥有排序功能。 Comparator则表示一个比较器,一般情况, 这个比较器将作为一个参数进行传递。 二.Comparable public interface Comparable<T> { public int...

HU1656的博客 340

Java——浅析Comparable与Comparator用法

文章目录Comparable与Comparator用法概述ComparableComparator案例总结共同点不同点 Comparable与Comparator用法 概述 Java中对集合对象或者数组对象排序,有两种方法 对象实现Comparable 接口 定义比较器,实现Comparator接口。 Comparable 1.包括实体类与实现comparable重写ComparaTo方法 写...

云祁QI 1246

浅析Java中Comparable与Comparator接口

我们在使用 Arrays.sort, Collections.sort 时会发现,调用该方法的类必须实现 Comparable接口,才能保证方法的正确调用,我们先来看Comparable 接口。 Comparable public interface Comparable<T> { public int compareTo(T o); } This interface impos...

EJoft的博客 429

Java - 浅析 Comparable 和 Comparator

Java - 浅析 Comparable 和 Comparator

业精于勤荒于嬉 371
上一篇: Java fail-fast 机制
下一篇: 使用 HashMap 存一万条数据,构造时传 10000 还会触发扩容吗?
ali48
博客等级 码龄6年 31粉丝 117原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值