1、实现ArrayList,并向其中加入int,String,和Person对象
解答:
package com.collectiontest;
import java.util.Objects;
public class Person {
private String name;
private int age;
public Person() {
}
public Person(String name, int age) {
this.name = name;
this.age = 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;
}
@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);
}
}
上面的Person类可以使用IDEA自动生成。
package com.collectiontest;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
public class CollectionTest2 {
@Test
public void test1() {
ArrayList list = new ArrayList();
list.add(123);
list.add(456);
list.add(123);
// 同一个包下的类不用带导入
list.add(new Person("Jerry", 20));
list.add(new String("Tom"));
list.add(false);
System.out.println(list.contains(123));
System.out.println(list.contains(new Person("Jerry", 20)));
System.out.println(list);
Collection coll1 = Arrays.asList(123, 4567);
System.out.println(list.containsAll(coll1));
}
}
测试结果: