容器方法举例

来源:互联网 发布:蒋介石为何不抵抗知乎 编辑:程序博客网 时间:2024/05/18 02:20

容器类对象在调用remove contains等方法需要比较对象是否相等,这会涉及到equals和hashCode方法;

对于自定义的类需要重写equals和hashCode方法以实现自定义类的对象的相等;

相等的对象应该具有hashcodes;

hashCode方法一般在对象最为map的键的时候使用;

import java.util.ArrayList;
import java.util.Collection;


public class Name {

 
 private String firstName,lastName;
 
 public Name(String firstName, String lastName) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result
    + ((firstName == null) ? 0 : firstName.hashCode());
  result = prime * result
    + ((lastName == null) ? 0 : lastName.hashCode());
  return result;
 }

 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Name other = (Name) obj;
  if (firstName == null) {
   if (other.firstName != null)
    return false;
  } else if (!firstName.equals(other.firstName)){
   return false;
  } 
  if (lastName == null) {
   if (other.lastName != null)
    return false;
  } else if (!lastName.equals(other.lastName)){
   return false;
  } 
  return true;
 }

 public static void main(String[] args) {
  Collection c=new ArrayList();
  c.add(new Name("wang","delei"));
  c.add(123);
  c.remove(new Name("wang","delei"));
  c.remove(123);
        System.out.println(c);
 }

}

运行结果:

[]


 

 

 

原创粉丝点击