Java代码中如何删除数组中的对象呢?

java问题王 Java每日一问 发布时间:2021-09-26 09:50:35 阅读数:13846 1
下文笔者讲述Java代码删除数组对象的方法分享,如下所示:
实现思路:
    1.将数组转换为list
	2.使用List的remove方法
	3.将List转换数组
 
例:
package com.java265.other;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class test {
	/*
	 * java265.com 数组中删除对象的示例分享
	 */
	public static void main(String[] args) throws Exception {
		A a[] = { new A("张三", 1), new A("李四", 2), new A("刘五", 3) };

		// 将数组转换为list
		List<A> list = new ArrayList<>();
		Collections.addAll(list, a);

		list.remove(1);
		list.toArray(a);

		for (A t : a) {
			System.out.println(t);
		}
	}
}

class A {
	private String name;
	private int age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

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

	@Override
	public String toString() {
		return "A [name=" + name + ", age=" + age + "]";
	}

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

	public A() {
		super();
	}
}
------运行以上代码,将会输出以下信息-----
A [name=张三, age=1]
A [name=刘五, age=3]
null
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaProblem/202109/1258.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者