Collection最基本方法:
- add
- addAll
- containsAll
- remove
- removeAll
- clear
- size
- isEmpty
import java.util.ArrayList;
import java.util.Collection;
public class TestCollection {
public static void main(String[] args) {
Collection col=new ArrayList();
col.add("jarvis");
col.add("boy");
col.add(18);
System.out.println("col = " + col);
Collection c=new ArrayList();
c.add("yu");
c.add("girl");
c.add(17);
((ArrayList) col).addAll(c);
System.out.println("after addAll ...");
System.out.println("col = " + col);
System.out.println("after containsAll ...");
System.out.println(col.containsAll(c));
col.remove(18);
System.out.println("after remove ...");
System.out.println("col = " + col);
col.removeAll(c);
System.out.println("after removeAll ...");
System.out.println("col = " + col);
boolean contains=col.contains("jarvis");
System.out.println("after contains test ...");
System.out.println("Jarvis"+( contains?"在":"不在"));
col.clear();
System.out.println("after clear ...");
System.out.println("col = " + col);
System.out.println("after size ...");
System.out.println("col.size 是"+col.size());
System.out.println("after isEmpty ...");
System.out.println("col.isEmpty? 是"+col.isEmpty());
}
}
如果元素是是一个其他类的对象呢?
元素是Person类:
import java.util.Objects;
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return age == person.age &&
Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
add和remove操作:
import java.util.ArrayList;
import java.util.Collection;
public class TestCollection {
public static void main(String[] args) {
Collection pers=new ArrayList();
pers.add(new Person("jarvis",18));
pers.add(new Person("robin",18));
pers.add(new Person("wzb",18));
pers.remove(new Person("jarvis",18));
System.out.println("pers = " + pers);
}
}
注意:只有在Person类重写(Override)equals和hashCode方法,才可以进行上述的remove