java去除重復(fù)對象的簡單實例
實例如下:
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;
}
}
public class ArrayListTest2{
public static void main(String args[])
{
ArrayList al=new ArrayList();
al.add(new Person("zhangsan1",22));
al.add(new Person("zhangsan2",33));
al.add(new Person("zhangsan3",44));
al.add(new Person("zhangsan5",88));
al.add(new Person("zhangsan4",55));
al.add(new Person("zhangsan1",22));
//al.add(new Person("zhangsan3",44));
al = singelElements(al);
Iterator it1=al.iterator();
while(it1.hasNext()){
Person p=(Person)it1.next();
sop(p.getName()+"..."+p.getAge());
}
/*Iterator it=al.iterator();
while(it.hasNext()){
Person p= (Person)it.next();//將其強制轉(zhuǎn)化為person類型 可以實現(xiàn)后邊的輸入否則不能調(diào)用getAge()和getName()方法
sop(p.getName()+"..."+p.getAge());
}*/
}
public static ArrayList singelElements(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);
}
}
解題思路:創(chuàng)建一個臨時容器ArrayList來存儲不重復(fù)的對象。通過兩次使用迭代器將對象取出從而輸入不重復(fù)的對象。
這里需要注意到在Person類中需要定義一個equals方法來比較是否有相同的元素。其中instance的用法是判斷對象是否屬于該類如果屬于則返回true否則返回false.
注意Java編程中ArrayLis等容器中調(diào)用contains以及remove方法時候都會調(diào)用equals方法。這是一個很多人都不注意的知識點。
以上就是小編為大家?guī)淼膉ava去除重復(fù)對象的簡單實例全部內(nèi)容了,希望大家多多支持腳本之家~
相關(guān)文章
Spring Boot實戰(zhàn)之逐行釋義Hello World程序
spring boot 是基于Spring的一個框架,Spring boot幫我們集成很多常用的功能,使得整個配置更加簡單。這篇文章主要介紹了Spring Boot實戰(zhàn)之逐行釋義Hello World,需要的朋友可以參考下2017-12-12
Java實戰(zhàn)員工績效管理系統(tǒng)的實現(xiàn)流程
只學(xué)書上的理論是遠遠不夠的,只有在實戰(zhàn)中才能獲得能力的提升,本篇文章手把手帶你用java+SSM+Mysql+Maven+HTML實現(xiàn)一個員工績效管理系統(tǒng),大家可以在過程中查缺補漏,提升水平2022-01-01
Java使用selenium爬取b站動態(tài)的實現(xiàn)方式
本文主要介紹了Java使用selenium爬取b站動態(tài)的實現(xiàn)方式,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-01-01
maven的pom.xml中repositories和distributionManagement使用
這篇文章主要介紹了maven的pom.xml中repositories和distributionManagement使用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03

