- package day9;
- import java.util.ArrayList;
- public class TestList {
- private String name;
- private int age;
- public TestList(String name, int age) {
- this.name = name;
- this.age = age;
- }
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- @Override
- public boolean equals(Object obj) {
- // TODO Auto-generated method stub
- if (obj != null) {
- if (obj instanceof TestList) {
- TestList w = (TestList) obj;
- if (w.getAge() == this.age && w.getName().equals(this.name))
- return true;
- }
- }
- return false;
- }
- @Override
- // 重写toString 方法,如果没有重写,则返回类地址和hashcode,而且每次返回的hashcode不一样。
- public String toString() {
- // TODO Auto-generated method stub
- return name + " is " + age + " year old。";
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- ArrayList<TestList> list = new ArrayList<TestList>();
- // 添加3个用户的信息
- list.add(new TestList("Tom", 24));
- //验证ArrayList中可以存放相同的元素(另外,HashSet里面不可以重复)
- list.add(new TestList("Stephen Chou", 52));
- list.add(new TestList("Stephen Chou", 52));
- // 测试重写equals方法的效果,如果没有重写,则返回false,重写后返回true。
- System.out.println("test overload equals():");
- System.out.println(list.get(1).equals(list.get(2)));
- System.out.println("--------------------------------");
- // 在第二个用户前插入一个用户的信息
- list.add(1, new TestList("Jay Chou", 35));
- // 删除第三个用户的信息
- list.remove(3);
- for (int i = 0; i < list.size(); i++) {
- System.out.println(list.get(i));
- }
- System.out.println("--------------------------------");
- //测试clear()方法。
- list.clear();
- System.out.println("clear后,还有多少元素? "+list.size());
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/2408201513522.html
来源: http://www.codesnippet.cn/detail/2408201513522.html