欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

集合,ArrayList练习

程序员文章站 2022-04-24 16:23:31
1 import java.util.ArrayList; 2 import java.util.Iterator; 3 4 public class ArrayListTest { 5 public static void main(String[] args) { 6 ArrayList lis... ......
 1 import java.util.ArrayList;
 2 import java.util.Iterator;
 3 
 4 public class ArrayListTest {
 5     public static void main(String[] args) {
 6         ArrayList<Person> list = new ArrayList<Person>();
 7           list.add(new Person("wangcai", 21));
 8           list.add(new Person("zhangsan", 22));
 9           list.add(new Person("lisi", 23));
10           list.add(new Person("zhaoliu", 24));
11           list.add(new Person("wangcai", 21));
12           list.add(new Person("lisi", 23));
13           System.out.println(list);
14           list=getNewList(list);
15           System.out.println(list);
16           singleStringDemo();
17     }
18     
19     public static void singleStringDemo(){
20           ArrayList list=new ArrayList();
21           list.add("java01");
22           list.add("java02");
23           list.add("java05");
24           list.add("java02");
25           list.add("java04");
26           list.add("java05");
27           list.add("java04");
28           System.out.println(list);
29           list=getNewList(list);
30           System.out.println(list);
31     }
32 
33     public static ArrayList getNewList(ArrayList list) {
34         ArrayList temp = new ArrayList();
35         Iterator it = list.iterator();
36         while(it.hasNext()) {
37             Object obj = it.next();
38             if (!temp.contains(obj)) {
39                 temp.add(obj);
40             }
41         }
42         return temp;
43     }
44 }
 1 public class Person {
 2     private String name;
 3     private int age;
 4     
 5     public Person() {
 6         super();
 7     }
 8 
 9     public Person(String name, int age) {
10         super();
11         this.name = name;
12         this.age = age;
13     }
14 
15     public String getName() {
16         return name;
17     }
18 
19     public void setName(String name) {
20         this.name = name;
21     }
22 
23     public int getAge() {
24         return age;
25     }
26 
27     public void setAge(int age) {
28         this.age = age;
29     }
30 
31     @Override
32     public String toString() {
33         return "Person [name=" + name + ", age=" + age + "]";
34     }
35     
36 }