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

示例1

  • 前提:

    新建一个主类Demo1

  • 需求:

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

  • 结果:

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

demo

示例2

  • 前提:

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

  • 需求:

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

  • 结果:

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

demo

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;
	}

}
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 方法。

	@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;
	}

成功删除

demo

拓展

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

demo

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

在进入项目后这种问题其实不用担心,但是你可以多掌握一点原理。
因为工作中的项目一般会引入Lombok,然后使用注解解决这些繁琐的小问题。

demo

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>