Java编程:定义功能去除ArrayList中的重复元素

本文探讨了如何在Java中手动实现去除ArrayList中的重复元素,强调了编程思路的重要性。通过创建一个临时容器,对比每个新元素与已有的元素,避免添加重复项。在处理对象比较时,讲解了如何复写equals方法来达到比较目的,并给出了完整的代码示例,最终展示成功去除重复元素的结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

     中午做了一个奇奇怪怪的梦,说是白日梦那也太离奇了吧~~今天是国庆第5天,开始技术!

      说道ArrayList大家头脑中肯定能想到,ArrayList内部是数据链接列表实现(链表数据结构);是不同步的(效率高),增删速度快;有角标,但底层是链表结构。那么问题来了,既然ArrayList中没有自带的取出重复元素的功能,那么我们自己实现一个吧(这也是机试中常常出现的题)。

      在编程前好好想想编程思路,这是很重要的。那么这个简单编程的编程思路是什么呢:

      首先,肯定是将元素存入ArrayList中;然后,定义一个临时容器,每次存放一个对象的时候与已有对象进行比较,临时容器中没有则存入,反之舍弃。可以看出思路非常简单。但是在具体写的时候会遇到一些问题。

      其中最大的问题就是对象和对象之间如何进行比较?我很自然的就想到了contains这个函数方法,如果是在String类型之间进行比较,那么这个方法直接实用就行。底层代码如下:

/**
     * Returns <tt>true</tt> if this list contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this list contains
     * at least one element <tt>e</tt> such that
     * <tt>(o==null ? e==null : o.equals(e))</tt>.
     *
     * @param o element whose presence in this list is to be tested
     * @return <tt>true</tt> if this list contains the specified element
     */
    public boolean contains(Object o) {
	return indexOf(o) >= 0;
    }

    /**
     * Returns the index of the first occurrence of the specified element
     * in this list, or -1 if this list does not contain the element.
     * More formally, returns the lowest index <tt>i</tt> such that
     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
     * or -1 if there is no such index.
     */
    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]))
		    return i;
	}
	return -1;
    }

      但这里是在对象见进行比较,难道我们复写contains方法吗?肯定不用这样子啊。我们了解contains方法之后就会发现完全不用复写contains方法,contains的执行过程是:将传递进的元素和本元素使用equals()进行循环比较,如果equals返回真,则表示包含此元素,反之则不包含。

      简而言之就是,我们只需要复写自定义Person类中的equals方法即可。我们复写的方式如下:

public boolean equals(Object obj) {
		
		if(this==obj)
			return true;
		if(!(obj instanceof Person))
			throw new ClassCastException();//类型错误
		
		Person p = (Person)obj;
		System.out.println(this+"...equal..."+p.name);
		return this.name.equals(p.name)&&this.age==p.age;
	}
Person中其余代码在前几篇博文中已有提到,在这里就是赘述。

那么整体的代码是:

public class ArrayListTest {

	/*
	 * 定义功能去除ArrayList中的重复元素
	 */
	public static void main(String[] args) {		
				
		//singleString(); //存储字符串
		
		//存自定义对象
		ArrayList al = new ArrayList();
		al.add(new Person("linweieran",24));
		al.add(new Person("linweieran1",23));
		al.add(new Person("linweieran2",22));
		al.add(new Person("linweieran3",25));
		al.add(new Person("linweieran",24));
		System.out.println(al);
		
		al=getSingleElement(al);
		System.out.println(al);
				
	}
		
	public static ArrayList getSingleElement(ArrayList al) {
		//1.定义一个临时容器
		ArrayList temp=new ArrayList();
		
		//2.迭代al集合
		Iterator it=al.iterator();
		
		while(it.hasNext()){
			Object obj=it.next();
			
			//3.判断被迭代到的元素是否在临时容器中存在
			if(!temp.contains(obj)){
				temp.add(obj);   //依据equals来判断是否包含。
			}
		}
		
		
		return temp;
	}


      在这个代码中当每次运行equals时为了方便理解代码运行过程,就会有equals字段提示。

运行结果如下:
去除重复元素成功!哈哈


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值