/*此代码用来获取一个ArryList集合中的唯一元素,并存入新的集合中
要实现该方法:
1.新建一个ArryList数集合
2.通过创建迭代器的方法遍历要操作集合的元素
3.通过新建集合的boolean contains()方法查看遍历的元素是否在该集合内
4.如果该集合没有该元素,就调用该集合的add()方法添加该元素,否者不做任何操作
5.遍历输出新集合
*/
import java.util.*;
class Text_ArrayListOnlyOne {
public static void main(String[] args) {
ArrayList arr = new ArrayList();
arr.add(new Person("zhangsan",23));
arr.add(new Person("lisi",24));
arr.add(new Person("lisi",24));
arr.add(new Person("wangwu",25));
arr.add(new Person("zhaoliu",26));
ArrayList arr1 = onlyOne(arr);
System.out.println(arr1.size());
Iterator it = arr.iterator();
while (it.hasNext()) {
Person p = (Person) it.next();
System.out.println(p.getAge()+"..."+p.getName());
}
}
public static ArrayList onlyOne (ArrayList arr){
ArrayList arry = new ArrayList();
Iterator it = arr.iterator();
while (it.hasNext()) {
Person p = (Person) it.next();
if (!(arry.contains(p))) {
arry.add(p);
}
}
return arry;
}
}
class Person implements Comparable{
private String name;
private int age;
Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public int compareTo(Object obj){
if(!(obj instanceof Person)){
throw new RuntimeException("非人类");
}
Person p = (Person) obj;
int a = this.getName().compareTo(p.getName());
if (a == 0) {
return this.getAge()-p.getAge();
}
return a;
}
public boolean equals(Object obj){
Person p = (Person) obj;
return this.getName() == p.getName() & this.getAge() == p.getAge();
}
}
//创建一个比较器(就是创建一个实现Comparator接口,并复写compare()方法的类)
//用来传给TreeSet的构造函数
class My_Comparator implements Comparator{
public int compare(Object ob1,Object ob2){
Person p1 =(Person)ob1;
Person p2 =(Person)ob2;
int a = p2.getName().compareTo(p1.getName());
if (a==0) {
return new Integer(p2.getAge()).compareTo(new Integer(p1.getAge()));
}
return a;
}
} |