17-集合框架-20-常用对象API(集合框架练习)

package cn.itcast.bean.person;

public class Person {

	private String name;
	private int 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;
	}

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

	public Person() {
		super();

	}

	@Override
	public boolean equals(Object obj) {

		if (this == obj) {
			return true;
		}
		if (!(obj instanceof Person)) {
			throw new ClassCastException("类型错误");
		}
		Person p = (Person) obj;
		return this.name.equals(p.name) && this.age == p.age;
	}

}

=================================================================分割线==============================================================

package cn.itcast.collection.test;


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


public class CollectionTest {


public static void main(String[] args) {


/*
* 【需求】
* 删除ArrayList中重复元素
*/
ArrayList al = new ArrayList();
al.add("abc1");
al.add("abc2");
al.add("abc2");
al.add("abc1");
al.add("abc");

System.out.println(al);
al=getSingleElement(al);
System.out.println(al);
}


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);
}


return temp;
}


}

=================================================================分割线==============================================================

package cn.itcast.collection.test;


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


import cn.itcast.bean.person.Person;


public class CollectionTest2 {


public static void main(String[] args) {


ArrayList al = new ArrayList();


al.add(new Person("lisi1", 21));
al.add(new Person("lisi2", 22));
al.add(new Person("lisi3", 23));
al.add(new Person("lisi4", 24));
al.add(new Person("lisi3", 23));
al.add(new Person("lisi4", 24));


printArrayList(al);
System.out.println("======================");

al = getSingleElement_2(al);


printArrayList(al);
}


public static void printArrayList(ArrayList al) {
Iterator i = al.iterator();
while (i.hasNext()) {
Person p = (Person) i.next();
System.out.println(p.getName() + "..." + p.getAge());
}
}


public static ArrayList getSingleElement_2(ArrayList al) {


ArrayList temp = new ArrayList();
Iterator it = al.iterator();
while (it.hasNext()) {
Object obj = it.next();
if (!(temp.contains(obj)))
temp.add(obj);
}
return temp;
}


}

你可能感兴趣的:(17-集合框架-20-常用对象API(集合框架练习))