116.01 16.02去除重复的元素
这个代码很巧妙,不要忘记contains这个方法
contains 和 remove底层都是依赖equals方法,equals方法这个需要重写的
package com.heima.list;
import java.util.ArrayList;
import java.util.Iterator;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class Demo1_ArrayList {
/**
* * A:案例演示
* 需求:ArrayList去除集合中字符串的重复值(字符串的内容相同)
* 思路:创建新集合方式
*/
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("a");
list.add("a");
list.add("b");
list.add("b");
list.add("c");
list.add("c");
list.add("c");
list.add("c");
ArrayList newList = getSingle(list);
System.out.println(newList);
}
/*
* 创建新集合将重复元素去掉
* 1,明确返回值类型,返回ArrayList
* 2,明确参数列表ArrayList
*
* 分析:
* 1,创建新集合
* 2,根据传入的集合(老集合)获取迭代器
* 3,遍历老集合
* 4,通过新集合判断是否包含老集合中的元素,如果包含就不添加,如果不包含就添加
*/
public static ArrayList getSingle(ArrayList list) {
ArrayList newList = new ArrayList<>(); //1,创建新集合
Iterator it = list.iterator(); //2,根据传入的集合(老集合)获取迭代器
while(it.hasNext()) { //3,遍历老集合
Object obj = it.next(); //记录住每一个元素
if(!newList.contains(obj)) { //如果新集合中不包含老集合中的元素
newList.add(obj); //将该元素添加
}
}
return newList;
}
}
package com.heima.list;
import java.util.ArrayList;
import java.util.Iterator;
import com.heima.bean.Person;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class Demo2_ArrayList {
/**
* * A:案例演示
* 需求:ArrayList去除集合中自定义对象元素的重复值(对象的成员变量值相同)
* B:注意事项
* 重写equals()方法的
contains方法判断是否包含,底层依赖的是equals方法
remove方法判断是否删除,底层依赖的是equals方法
*/
public static void main(String[] args) {
ArrayList list = new ArrayList(); //创建集合对象
list.add(new Person("张三", 23));
list.add(new Person("张三", 23));
list.add(new Person("李四", 24));
list.add(new Person("李四", 24));
list.add(new Person("李四", 24));
list.add(new Person("李四", 24));
//ArrayList newList = getSingle(list); //调用方法去除重复
//System.out.println(newList);
list.remove(new Person("张三", 23));
System.out.println(list);
}
/*
* 创建新集合将重复元素去掉
* 1,明确返回值类型,返回ArrayList
* 2,明确参数列表ArrayList
*
* 分析:
* 1,创建新集合
* 2,根据传入的集合(老集合)获取迭代器
* 3,遍历老集合
* 4,通过新集合判断是否包含老集合中的元素,如果包含就不添加,如果不包含就添加
*/
public static ArrayList getSingle(ArrayList list) {
ArrayList newList = new ArrayList<>(); //1,创建新集合
Iterator it = list.iterator(); //2,根据传入的集合(老集合)获取迭代器
while(it.hasNext()) { //3,遍历老集合
Object obj = it.next(); //记录住每一个元素
if(!newList.contains(obj)) { //如果新集合中不包含老集合中的元素
newList.add(obj); //将该元素添加
}
}
return newList;
}
}
package com.heima.bean;
public class Person {
private String name;
private int age;
public Person() {
super();
}
public Person(String name, int age) {
super();
this.name = name;
this.age = 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 "Person [name=" + name + ", age=" + age + "]";
}
/*@Override
public boolean equals(Object obj) {
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.age;
}*/
}