1. 通过重写hashCode, equals 方法 实现对ArrayList 去重。
package day18;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
class Per implements Comparable {
String Name;
int Age;
Per(String Name ,int Age){
this.Age=Age;
this.Name =Name;
}
@Override
public String toString() {
return "Name :"+Name+"Age:"+Name;
}
@Override
public int hashCode() {
System.out.println(this.Name+"hashcode");
return Name.hashCode()+39*Age;
}
@Override
public boolean equals(Object obj) {
if(obj==this){
return true;
}
if(!(obj instanceof Per )){
throw new ClassCastException("类型错误");
}
Per per =(Per)obj;
System.out.println(this.Name+" equals ");
boolean ret=(this.Name.equals(per.Name) && this.Age == per.Age);
System.out.println("equals ===="+ret);
return ret ;
}
@Override
public int compareTo(Object o) {
Per p = (Per)o;
int temp = this.Age-p.Age;
return temp==0?this.Name.compareTo(p.Name):temp;
// int temp = this.name.compareTo(p.name);
// return temp==0?this.age-p.age:temp;
/*
if(this.age>p.age)
return 1;
if(this.age<p.age)
return -1;
else{
return this.name.compareTo(p.name);
}
*/
}
}
/**
* Created by zengjx on 2019/5/24.
*/
public class ArrayListTest {
public static void main(String[] args){
test1();
}
public static void test1(){
ArrayList arrayList =new ArrayList();
arrayList.add(new Per("aa",1));
arrayList.add(new Per("bb",2));
arrayList.add(new Per("cc",3));
arrayList.add(new Per("cc",3));
/* arrayList.add("1111");
arrayList.add("2222");
arrayList.add("2222");*/
// System.out.println(arrayList.remove(new Per("aa",1)));// remove 里面调用的是 equals ,
// Per 类的 equals 被重写了 ,比较的是值 所以可以删除
// System.out.println(arrayList);
// show(arrayList);
// ArrayList newArr= getSingleElement (arrayList);
ArrayList newArr= single (arrayList);
// show(newArr);
System.out.println(newArr);
}
/*
contains 其实就是依据 equals 方法
public boolean contains(Object o)如果此列表中包含指定的元素,则返回 true。更确切地讲,当且仅当此列表包含至少一个满足
(o==null ? e==null : o.equals(e)) 的元素 e 时,则返回 true。
*/
public static ArrayList single(ArrayList arrayList){
ArrayList temp=new ArrayList();
Iterator it =arrayList.iterator();
while(it.hasNext())
{
// Per per= (Per)it.next();
Per per=(Per) it.next();
if( !temp.contains(per) )
{
temp.add(per);
}
}
return temp;
}
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);
}
}*/
while(it.hasNext()){
Per per=(Per) it.next();
//3,判断被迭代到的元素是否在临时容器存在。
if(!temp.contains(per)){
temp.add(per);
}
}
return temp;
}
public static void show(ArrayList arrayList){
Iterator it=arrayList.iterator();
while (it.hasNext()){
Per per=(Per)it.next();
System.out.println(per.Age+" & "+per.Name);
}
System.out.println("----- ");
}
}