ArrayList的contains方法,底层调用了equals方法

ALUBI LPMS-IG1 IMU在ROS2中的完整配置指南(含Windows上位机调试技巧) 本文详细介绍了ALUBI LPMS-IG1 IMU在ROS2环境中的完整配置流程,包括Windows上位机调试和Ubuntu驱动安装。特别针对RS232接口版本的跨平台参数同步问题提供解决方案,帮助开发者快速实现高精度惯性测量单元的数据采集与处理。 阅读详情

题目:

将自定义对象作为元素存到ArrayList集合中,并去除重复元素
比如:存人对象,同姓名,同年龄,视为同一个人,为重复元素。

/*
思路
1对人描述,将数据封装进人对象
2定义容器,将人存入
3取出
*/
import java.util.*;
class Person
{
        private String name;
        private int age;
        Person(String name,int age)
        {
                this.name= name;
                this.age= age;
        }
        public boolean equals(Object obj)
        {
                if(!(obj instanceof Person))
                        return false;
 
                Person p= (Person)obj;
                return this.name.equals(p.name)&& this.age == p.age;
        }
        public String getName()
        {
                return name;
        }
        public int getAge()
        {
                return age;
        }
}
 
class Test
{
        public static void main(String[] args)
        {
                ArrayList al = new ArrayList();
 
                al.add(new Person("lisi01",30));
                al.add(new Person("lisi02",35));
                al.add(new Person("lisi03",32));
                al.add(new Person("lisi02",35));
                al.add(new Person("lisi03",32));
                al.add(new Person("lisi04",31));
 
                al=singleElement(al);
 
                Iterator it = al.iterator();
 
                while (it.hasNext())
                {
                        Person p = (Person)it.next();
                        sop(p.getName()+"---"+p.getAge());
                }
        }
 
        public static ArrayList singleElement(ArrayList al)
        {
                //定义一个临时容器
                ArrayList newAl = new ArrayList();
                Iterator it =al.iterator();
                 
                while (it.hasNext())
                {
                        Object obj = it.next();
                        if (!newAl.contains(obj))
                                newAl.add(obj);
                }
                return newAl;
        }
 
        public static void sop(Object obj)
        {
                System.out.println(obj);
        }
}


public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }
    public int indexOf(Object o) {
        if (o == null) {
            for (int i = 0; i < size; i++)
                if (elementData[i]==null)
                    return i;
        } else {
            for (int i = 0; i < size; i++)
                if (o.equals(elementData[i]))    //调用参数的equals方法
                    return i;
        }
        return -1;
    }
















Qualcomm工具的使用 简介   由于我们公司主要是以高通平台为主,所以工具的使用是必不可少的,包括QPST、QRCT3、QXDM、QDART等。   高通工具顾名思义就是,对于高通平台的软件开发进行软件的烧录,软件的调试,软件的Log的抓取和分析过程,像我们平常用的大致就是烧版本、改NV、制作QCN、然后校准、强发强收等操作。 QPST   QPST主要是用来做一些参数的配置,包括EFS文件的编辑,QCN的导入和备份与... 阅读详情

相关推荐

多个MOS管并联应用场景的四大要点

动态运行时,阈值电压Vgsth最低的MOS管首先打开,最后关闭。这种MOS管一般会占据更多的开关损耗,并且在开关转换过程中,承担了更高的电应力。

VBsemi的博客 3748

详述ArrayList类contains方法

一、源码: //源码1 public boolean contains(Object o) { return indexOf(o) >= 0; } //源码2 public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++) if (elementData[i]==null) return i;

weixin_42867975的博客 461

Netapp FAS2750更换磁盘后不同步问题处理

netapp fas2750磁盘更换后不同步问题处理

jetliu05的博客 1256

详述Java中ArrayList类contains方法

源码 contains: public boolean contains(Object o) { return indexOf(o) >= 0; } indexOf: public int indexOf(Object o) { if (o == null) { for (int i = 0; i < size; i++...

FOREVER_GWC的博客 585

2024从零开始使用VSCode编程(静态页面制作篇)HTML+CSS+JS阶段

VSCode第一个前端静态页面的编写

ssrsrrn的博客 9590

Cleo Synchronization接口任意文件读取漏洞CVE-2024-50623 附POC

微信公众号搜索:南风漏洞复现文库该文章 南风漏洞复现文库 公众号首发Cleo。

nnn2188185的博客 480

ArrayList 中 contains remove 判断元素相同 底层调用了 equals方法

我们有时候需要判断arraylist容器中是否已经存了某个元素,那么调用contains(object)方法就可以了,他的返回值是boolean类型,若有已经存在某元素则返回true,如果不存在则返回false。 比如 package info.dyndns.oszc; import java.util.*; public class Utils { public static v

zzcchunter的专栏 4924

手把手教您如何群晖/飞牛NAS等服务器上一键部署洛雪音乐同步服务,手机电脑无缝同步歌单,支持外网访问

🎵 手机电脑歌单不同步?用Docker在群晖/飞牛NAS等服务器上搭个同步服务器, 3分钟搞定 !支持docker-compose一键部署,手机、电脑、平板收藏夹实时同步,外出也能用域名远程访问 ~ ✨

XiaoqiangClub的博客 4601

详述:ArrayList类contains方法

文章目录源码1、String类型1.1、String类的分析方法2、包装类类型2.1、包装类类型的分析方法3、自定义类类型3.1、如何解决类类型中无法比较的问题?3.2、为什么重写之后需要加instanceof? 源码 public boolean contains(Object o) { return indexOf(o) >= 0; } public int inde...

核桃仁先生的博客 501

【运动规划算法项目实战】全覆盖分区算法

全覆盖规划在机器人学领域具有重要意义,其应用场景涵盖了自动农场、扫地机器人、扫描监视无人机等多个领域。该问题的核心目标是使机器人能够从指定起点出发,规划一条避开障碍物、同时路径尽可能短的轨迹,从而实现对特定区域的全面覆盖。在实际应用中,全覆盖规划的成功实现对于提高机器人在各类环境中的工作效率至关重要。这一问题的解决涉及到高效的路径规划和规划区域分解技术。其中,梯形单元分解算法是一种常用分区的技术,过将地图上需要规划的区域进行分区,采用梯形分解的方式,可以更好地应对复杂环境。全覆盖算法规划流程。

xiewf的博客 1万+

4.26华为OD机试真题 新系统 - 端口流量统计 (Java/Py/C/C++/Js/Go)

本文整理华为 OD 机试新系统机考真题库,涵盖高频考点精析与完整题目内容,提供 C 语言、Java、C++、Python、Go、JavaScript 多语言源码实现,搭配详细解题思路讲解,并支持在线 OJ 刷题练习,助力高效备考华为 OD 机试新系统。

算法大师! 2333

ArrayList的contains方法,底层调用了equals方法。

题目:将自定义对象作为元素存到ArrayList集合中,并去除重复元素比如:存人对象,同姓名,同年龄,视为同一个人,为重复元素。/* 思路 1对人描述,将数据封装进人对象 2定义容器,将人存入 3取出 */ importjava.util.*; classPerson { privateStringname; privateinta...

weixin_34205076的博客 198

大模型之Spring AI实战系列(二十一):Spring AI + MCP + 本地文件系统实战指南

在上一篇文章中,我们学习了如何使用 Spring AI 集成 Model Context Protocol (MCP),并通过 Brave Search 实现了互联网搜索能力的接入。本文将继续深入 Spring AI 的 MCP 实战能力,介绍如何将 **本地文件系统** 封装为 LLM 可调用的工具

寻道AI,探索AI无限可能! 2518

ArrayList类contains方法底层代码分析

我们知道在ArrayList类中contains是常用的方法之一,用来判断集合中是否存在用来判断的元素,那么contains方法到底是怎么执行的呢?我们今天来加以探究。 底层代码 我们可以看到,contains方法调用了indexof方法,传入o,这个o此时为上转型对象,是我们想用来判断集合中是否存在的那个元素,我们接着分析indexOf代码。 我们可以看到indexoj只有一个if...

zhaobin0731的博客 293

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

去掉空值 去重_集合框架:ArrayList去重

需求:如果集合里出现了姓名和年龄都相同的人,就说明是一个人,把重复的去掉First:首先得定义一个person类。Second:定义一个对集合去重的类然后,主函数开始创建集合,给集合里添加person现在输出一下所有元素的姓名和年龄,发现拿不到姓名,调不出来getName和getAge方法,这是为什么?因为al.add 在添加person的时候 add方法的参数是一个object类型,而add里面...

weixin_39955421的博客 106

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

向集合中添加自定义类型--建议在自定义类型的时候要重写equals方法

package com.bjpowernode.t01list; import java.util.ArrayList; /* * 向集合中添加自定义类型 */public class TestList04 { public static void main(String[] args) { ArrayList list = new ArrayList(); Student s1 = ...

weixin_30772105的博客 138

深度学习工具包 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")

ArrayList中的contains方法

首先看一下调用效果: public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>() ; list.add("Tom"); System.out.println(list.contains("Tom")); } 明显结果是true: 但是我...

low1101的博客 2043

浅析Java底层代码——ArrayList类contains方法

目录 一、contains底层代码 二、代码示例分析 (1)集合中元素对应类重写了Object类的equals()方法。 a、直接赋值创建String类对象 b、new关键字创建String类对象 (2)集合中元素对应类未重写Object类的equals()方法。 一、contains底层代码 在我之前的博客,Java中的HashSet的常用方法总结中提到过contai...

Liuxiaoyang1999的博客 554

ArrayList集合中contains方法底层代码分析

在ArrayList类集合中很常用的方法之一就是contains()方法,它可以判断一个集合中是否含有指定元素,知其然更要知其所以然,知道了它的作用后为了以后能更好的使用它,我们以举几个示例来来分析一下底层代码。 1.第一个示例 package contains; import java.util.ArrayList; public class Test { public stati...

ANFO的博客 966

分析ArrayList实现类中contains()方法底层代码

contains()方法是我们用于判断一个集合中是否含有某一元素的方法,那么作为ArrayList.util所提供的方法,它又是怎样实现的呢?本篇博客将深入contains()方法的底层代码,探究其实现原理。 情形一:参数存在 实例 import java.util.ArrayList; public class Test { public static void main(S...

飞翔的企鹅的博客 1021

ArrayList之removeAll底层原理实现详解

今天给大家介绍下ArrayList之removeAll的用法,并深入讲解一下它的底层实现原理。 大家先看如下所示代码: CollectionTest collectionTest =new CollectionTest(); List<DataDto> list1 =new ArrayList<>(); for(int ...

林老师带你学编程 3388

彻底搞懂ArrayList的contains方法

ArrayList的contains方法 用途 用于判断在ArrayList中是否包含目标元素 原理 调用indexOf(Object o)方法 public boolean contains(Object o) { return indexOf(o) >= 0; } indexOf(Object o)方法中调用传入Object对象的equals方法进行比较 public int indexOf(Object o) { // 传入的Object是null, 则在集合中

qq_38685072的博客 3967

ArrayList类contains方法实现原理

以ArrayList集合示例 思考:contains方法如何执行? public static void main(String [] args){ List<String> list=new ArrayList<String>(); list.add("张三"); System.out.println(list.contains("张三"); } 分析contains底层代码 public boolean contains(Object o) { //

qq_43842093的博客 2079

详述ArrayList类中的contains方法

详述ArrayList类中的contains方法 一、contains方法的参数是String类型 import java.util.ArrayList; public class Test { public static void main(String[] args) { ArrayList<String> nameList = new ArrayList<&g...

weixin_43964847的博客 2115

java arraylist equal_Java集合之List的equals方法

一、先说结论:1、List(ArrayList)调用equals方法,判断的是存储的元素相等,而不是直接比较引用。说明List(ArrayList)重写了equals方法。List l1 = new ArrayList<>();l1.add(T1);List l2 = new ArrayList<>();l2.add(T1);l1.equals(l2); //true2、L...

weixin_35990581的博客 1917

Java:ArrayList中的contains方法

String: 首先看一下调用效果: public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>() ; list.add("Tom"); System.out.println(list.contains("To...

bravery__的博客 1400
上一篇: JAVA算法_快速排序
下一篇: 解决CommonFileUpload上传文件不能获取多选框
CapMIS
博客等级 码龄21年 4粉丝 45原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值