###16.01_集合框架(去除ArrayList中重复字符串元素方式)(掌握)
* A:案例演示
* 需求: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("b");
list.add("c");
list.add("c");
list.add("c");
list.add("c");
System.out.println(list);
ArrayList newList = getSingle(list);
System.out.println(newList);
}
/*
* 去除重复
* 1,返回ArrayList
* 2,参数列表ArrayList
*/
public static ArrayList getSingle(ArrayList list) {
ArrayList newList = new ArrayList(); //创建一个新集合
Iterator it = list.iterator(); //获取迭代器
while(it.hasNext()) { //判断老集合中是否有元素
String temp = (String)it.next(); //将每一个元素临时记录住
if(!newList.contains(temp)) { //如果新集合中不包含该元素
newList.add(temp); //将该元素添加到新集合中
}
}
return newList; //将新集合返回
}
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;
}
}
###16.02_集合框架(去除ArrayList中重复自定义对象元素)(掌握)
* A:案例演示
* 需求:ArrayList去除集合中自定义对象元素的重复值(对象的成员变量值相同)
* B:注意事项
* 重写equals()方法的
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;
}*/
}
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(S