集合类

为什么出现集合类?

        面向对象对事物的体现都是以对象的形式,所以为了方便对多个对象的操作,就对对象进行存储,集合就是存储对象最常用的一种方法。

典型的集合应用于面向对象的应用

package collection;


import java.util.ArrayList;

import java.util.Iterator;


public class ArrayListDemo1 {

public static void main(String[] args) {

ArrayList arrayList = new ArrayList();

arrayList.add(new Person("lisi01", 30));

arrayList.add(new Person("lisi01", 30));

arrayList.add(new Person("lisi02", 33));

arrayList.add(new Person("lisi03", 33));

System.out.println(arrayList);

arrayList = singleElement(arrayList);

Iterator iterator = arrayList.iterator();

while (iterator.hasNext()) {

Person p = (Person) iterator.next();

System.out.println(p.getName() + ":" + p.getAge());

}

}

private static ArrayList singleElement(ArrayList arrayList) {

ArrayList arrayList2 = new ArrayList();

Iterator iterator = arrayList.iterator();

while (iterator.hasNext()) {

Object object = iterator.next();

if (!arrayList2.contains(object)) {

arrayList2.add(object);

}

}

return arrayList2;

}

}

class Person {

String name;

int age;

public boolean equals(Object obj) {

if (!(obj instanceof Person))

return false;

Person p = (Person) obj;

return this.name.equals(p.name) && this.age == p.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;

}

}

数组和集合类同是容器,有何不同?

         数组虽然也可以存储对象,但长度是固定的,集合长度是可变的,数组中可以存储基本数据类型,集合只能存储对象。

你可能感兴趣的:(集合类)