set存储对象出现重复的解决办法

package com.student.vo;

public class people {
	private int id;
	private String name;
	private String tel;
	public people(int id,String name,String tel){
		this.id=id;
		this.name=name;
		this.tel=tel;
	}
    @Override
    public boolean equals(Object obj) {
        if(!(obj instanceof people)) {
            return false;
        }
        people b = (people)obj;
        if(this.id == b.id) {
            return true;
        }
        return false;
    }
    
    @Override
    public int hashCode() {
        return id;
    }
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getTel() {
		return tel;
	}
	public void setTel(String tel) {
		this.tel = tel;
	}
}

新建一个people类,在类中重写了HashSet的HashCode、equals方法,读者写的时候可以直接把代码截取粘贴到你自己想用的类中,HashCode方法中的id相当于主键也就是键值,只能是唯一的,HashSet为按照这个id判断是否是同一个对象进行去重操作。

我这边调用是在servlet中引用此类

package com.student.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.student.dao.impl.UserDAOImpl;
import com.student.factory.DAOFactory;
import com.student.vo.User;
import com.student.vo.people;

public class studentFind extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		String id=new String(request.getParameter("id").getBytes("iso-8859-1"),"utf-8");
		String username=new String(request.getParameter("username").getBytes("iso-8859-1"),"utf-8");
		//list vector存的值可以重复因此改用set
		Vector vector=new Vector(); 
		Vector vector1=new Vector();
		Vector vector2=new Vector();
		Vector vector3=new Vector();
		//采用hashset存储自定义的对象,之前试过用treeMap做了两三个小时都没有把键作为对象存储,总会报类型转换错误
		try {
				//按照优先级查询 姓名、电话号码、性别
				if(!id.equals("")){
				vector=DAOFactory.getUserDAOinstance().findName(id,username);
				vector1=DAOFactory.getUserDAOinstance().findTel(id,username);
				vector2=DAOFactory.getUserDAOinstance().findSex(id,username);
				vector3=DAOFactory.getUserDAOinstance().findPinyin(id,username);
				Set set = new HashSet();
				for(int i=0;i




你可能感兴趣的:(java基础)