Java_自定义实体类的列表List<T>调用remove()失败讲解

示例1

  • 前提:

    新建一个主类Demo1

  • 需求:

    在一个列表中有三条String的数据,想要使用remove(Object o)删掉其中一条。

  • 结果:

    remove(Object o)成功把数据删掉。

示例2

  • 前提:

    新建一个自定义实体类DataExample和一个主类Demo

  • 需求:

    在一个列表中有三条实体类的数据,想要使用remove(Object o)删掉其中一条。

  • 结果:

    得到失败数据,remove(Object o)根本没有起作用把数据删掉。

java 复制代码
public class DataExample {

	private final String name;
	private int age;

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

	public DataExample(String name) {
		this.name = name;
	}

	public String getName() {
		return this.name;
	}

	void setAge(int age) {
		this.age = age;
	}

	public int getAge() {
		return this.age;
	}

}
java 复制代码
import java.util.ArrayList;
import java.util.List;

public class Demo {

	public static void main(String[] args) {

		List<DataExample> test1 = new ArrayList<>();
		
		test1.add(new DataExample("1",1));
		test1.add(new DataExample("2",2));
		test1.add(new DataExample("3",3));

		test1.remove(new DataExample("3",3));
		
		for(int i=0;i<test1.size();i++) {
			System.out.println(test1.get(i).getName()+":"+test1.get(i).getAge());
		}
	}

}

通俗易懂知识讲解

以上两个示例都是List删除数据,唯一不同的是列表类型。一个是String,一个是自定义的实体类DataExample。

首先,remove(Object o)删除是需要作比较,也就是equals方法。

因为String已经实现了 equals 方法来比较字符串内容,因此可以直接使用 remove 方法来删除指定的字符串。

但是自定义的实体类DataExample并没有实现自己的 equals 方法,所以 remove 方法也就没有用。

所以一般来说,在新建自定义的实体类之后,会要重写一个属于自己的 equals 方法。

java 复制代码
	@Override
	public boolean equals(Object o) {
		if (o == this)
			return true;
		if (!(o instanceof DataExample))
			return false;
		DataExample other = (DataExample) o;
		if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName()))
			return false;
		if (this.getAge() != other.getAge())
			return false;
		return true;
	}

成功删除

拓展

自定义的实体类需要读的源码:Lombok的@Data注解

官网:https://projectlombok.org/features/Data

在进入项目后这种问题其实不用担心,但是你可以多掌握一点原理。

因为工作中的项目一般会引入Lombok,然后使用注解解决这些繁琐的小问题。

相关推荐
小叶学C++5 分钟前
【C++】类与对象(下)
java·开发语言·c++
ac-er88887 分钟前
PHP“===”的意义
开发语言·php
2401_854391089 分钟前
高效开发:SpringBoot网上租赁系统实现细节
java·spring boot·后端
Cikiss18 分钟前
微服务实战——SpringCache 整合 Redis
java·redis·后端·微服务
wxin_VXbishe18 分钟前
springboot合肥师范学院实习实训管理系统-计算机毕业设计源码31290
java·spring boot·python·spring·servlet·django·php
Cikiss19 分钟前
微服务实战——平台属性
java·数据库·后端·微服务
jk_10125 分钟前
MATLAB中decomposition函数用法
开发语言·算法·matlab
weixin_4640780726 分钟前
C#串口温度读取
开发语言·c#
无敌の星仔28 分钟前
一个月学会Java 第2天 认识类与对象
java·开发语言
OEC小胖胖33 分钟前
Spring Boot + MyBatis 项目中常用注解详解(万字长篇解读)
java·spring boot·后端·spring·mybatis·web