码迷,mamicode.com
首页 > 其他好文 > 详细

Collection方法之二 向集合中添加自定义的元素

时间:2017-03-16 18:52:13      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:pre   equal   override   重写   log   org   方法   util   stc   

新建一个Person类

package andycpp;

public class Person {
  private  String name;
  private Integer age;
  //get,set方法
 public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public Integer getAge() {
   return age;
  }
  public void setAge(Integer age) {
   this.age = age;
  }
  //构造器
 public Person(String name, Integer age) {
   super();
   this.name = name;
   this.age = age;
  }
  //toString方法
 @Override
  public String toString() {
   return "Person [name=" + name + ", age=" + age + "]";
  }
  
 }










package andycpp;

import Java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Date;

import org.junit.Test;

public class TestCollection { 
  @Test
  public void testCollection2(){
   Collection coll  = new ArrayList();
   //存入现成的,也可以存入自定义的
  coll.add(123);
   coll.add("AA");
   coll.add(new Date());
   coll.add("BB");
   
   Person p = new Person("MM",23);
   coll.add(p);
   System.out.println(coll);
   //6,contains(Object obj);判断集合中是否包含指定的obj元素,如果包含返回true,反之,返回false
   boolean b1 = coll.contains(123);
   System.out.println(b1);
   boolean b2 =coll.contains(p);
   System.out.println(b2);
  }
  
  
  输出

[123, AA, Thu Mar 16 11:38:57 CST 2017, BB, Person [name=MM, age=23]]
 true
 true





























package andycpp;

import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Date;

import org.junit.Test;

public class TestCollection { 
  @Test
  public void testCollection2(){
   Collection coll  = new ArrayList();
   //存入现成的,也可以存入自定义的
  coll.add(123);
   coll.add("AA");
   coll.add(new Date());
   coll.add("BB");
   
   
   coll.add(new Person("MM",23));
   System.out.println(coll);
   //6,contains(Object obj);判断集合中是否包含指定的obj元素,如果包含返回true,反之,返回false
   boolean b1 = coll.contains(123);
   System.out.println(b1);
   boolean b2 =coll.contains(new Person("MM",23));
   System.out.println(b2);
  }
  

输出

[123, AA, Thu Mar 16 11:42:16 CST 2017, BB, Person [name=MM, age=23]]
 true
 false


第二种情况new了两个对象,所以返回false

思考:为啥包含123是true,即b1是true,而我自定义的b2就是FALSE呢




当我们不希望出现这种情况的时候怎么做呢?




当你传入的元素的属性值,和现有的集合中的元素的属性值一样,我就认为是一个,返回true.




因此,需要重写Person里面的equals()方法,见下一篇Collection方法之三

 

Collection方法之二 向集合中添加自定义的元素

标签:pre   equal   override   重写   log   org   方法   util   stc   

原文地址:http://www.cnblogs.com/lanboy/p/6560842.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!