平时写些临时的代码都是放在Test.java里,不发上来估计过两天又被覆盖掉了;
- package com.itheima.io;
- import java.util.*;
- class Test
- {
- public static void main(String[] args)
- {
- ArrayList<Person> list = new ArrayList<Person>();
- list.add(new Person("person1",42));
- list.add(new Person("person4",23));
- list.add(new Person("person3",12));
- list.add(new Person("person4",23));
- list.add(new Person("person2",24));
- list.add(new Person("person3",12));
- list.add(new Person("person1",42));
- list.add(new Person("person2",24));
-
- delete_iterator(list);
- print(list);
- delete_for(list);
- print(list);
- }
- public static void print(ArrayList<Person> list)
- {
- for(Person p : list)
- System.out.println(p);
- }
- public static void delete_for(ArrayList<Person> list)
- {
- Person pi,pj;
- for(int i = 0; i<list.size();i++)
- {
- pi = list.get(i);//取元素
- for(int j =0;j<list.size();j++)
- {
- pj = list.get(j);//取元素
- if(j!=i)
- {
- if(pi.name.equals(pj.name)&&pi.age==pj.age)//如果两个相等
- {
- list.remove(pj);//移除pj
- j--;//list长度-1,所以下一个元素往前推1位;
- }
- }
- }
- }
- }
- public static void delete_iterator(ArrayList<Person> list)
- {
- ListIterator<Person> it = list.listIterator();
- while(it.hasNext())
- {
- Person p = it.next();
- int i = 0;//移动的次数
- while(it.hasNext())
- {
- Person p1 = it.next();
- if(p.name.equals(p1.name)&&p.age==p1.age)
- {
- it.remove();
- i--;//移除元素,相当于少移动一次;
- }
- i++;//向后移动了一次
- }
- for(;i>0;i--)//向前移动i次
- it.previous();//向前移动i次,使得外层while回到原来位置;
- }
- }
- }
- class Person
- {
- String name;
- int age;
- public String toString()
- {
- return "name="+name+",age="+age+";";
- }
- Person(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- }
复制代码
|