JAVA案例练习: 去除ArrayList中重复的字符串(字符串内容相同),去除重复的对象

package com.yqw.list;

import java.util.ArrayList;
import java.util.Iterator;

public class Demo_ArrayList extends Object {

/**
* ArrayList 1、去除集合中字符串的重复值(字符串内容相同) 2、自定义对象去重(对象成员变量相同)
*contains方法底层依赖 equals方法

*remove方法底层依赖 equals方法,注意要重写equals方法和toString方法
* @param args
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) {
ArrayList list = new ArrayList();
/**
* 1、字符串类型数据去重
*/
list.add("a");
list.add("b");
list.add("b");

/**
* 2、自定义对象去重(对象成员变量相同)
*/
ArrayList list2 = new ArrayList();
list2.add(new Person("张三", 23));
list2.add(new Person("李四", 24));
list2.add(new Person("李四", 24));
ArrayList list1 = Demo_ArrayList.getSingle(list2);
System.out.println(list1);

list1.remove(new Person("张三", 23)); //remove方法底层依赖 equals方法
System.out.println(list1);
}

public static ArrayList getSingle(ArrayList list) {
ArrayList newList = new ArrayList();

Iterator it = list.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (!newList.contains(obj)) { //contains方法底层依赖 equals方法
newList.add(obj);
}
}
return newList;
}
}

class Person {
private String name;
private int age;

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

public Person() {
super();
}

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 "Person [name=" + name + ", age=" + age + "]";
}

@Override
public boolean equals(Object obj) {
Person p = (Person) obj;
if (this.name.equals(p.name) && this.age == p.age) {
return true;
} else {
return false;
}
}
}

上一篇:Android课程---首学开发


下一篇:https大势已来?看腾讯专家如何在高并发压测中支持https