java list中的对象去重原理

/******************************************************************************* 
 * 
 * Copyright (c) Weaver Info Tech Co. Ltd 
 * 
 * SessionInfo 
 * 
 * app.backend.model.SessionInfo.java 
 * TODO: File description or class description. 
 * 
 * @author: Administrator 
 * @since:  2014-5-26 
 * @version: 1.0.0 
 * 
 * @changeLogs: 
 *     1.0.0: First created this class. 
 * 
 ******************************************************************************/  

  
import java.io.Serializable;  
  
/** 
 * @author Administrator 
 * 
 */  
@SuppressWarnings("serial")  
public class SessionInfo implements Serializable{  
    private int id;  
    private String url;  
    public int getId() {  
  
        return id;  
    }  
    public void setId(int id) {  
  
        this.id = id;  
    }  
  
    public String getUrl() {  
  
        return url;  
    }

    @Override
    public String toString() {
        return "SessionInfo{" +
                "id=" + id +
                ", url='" + url + '\'' +
                '}';
    }

    public void setUrl(String url) {
  
        this.url = url;  
    }  
  
    /* (non-Javadoc) 
     * @see java.lang.Object#hashCode() 
     */  
    @Override  
 public int hashCode() {  
        return id;  
    }  
  
    /* (non-Javadoc) 
     * @see java.lang.Object#equals(java.lang.Object) 
     */  
    @Override  
 public boolean equals(Object o) {  
        if (o == null) {  
            return false;  
        } else {  
            if (o.getClass() != this.getClass()) {  
                return false;  
            } else {  
                final SessionInfo s = (SessionInfo) o;  
                return s.id == this.id;  
            }  
        }  
    }  
}  

 

import java.util.*;

public class HashCodeTest {  
  

  
    public static void main(String[] args){  


        SessionInfo sessionInfo1 = new SessionInfo();
        SessionInfo sessionInfo2 = new SessionInfo();
        sessionInfo1.setId(1);
        sessionInfo2.setId(1);
        sessionInfo1.setUrl("test");
        sessionInfo2.setUrl("test");


        SessionInfo mSessionInfo = null;                    //实体类对象
        Set<SessionInfo> sessionList = new HashSet<SessionInfo>();  //声明set集合对象
        final List<SessionInfo> list = new ArrayList<SessionInfo>();//声明list集合对象


        sessionList.add(sessionInfo1);//将对象添加到Set集合中
        sessionList.add(sessionInfo2);//将对象添加到Set集合中
        list.addAll(sessionList);//将数据添加到list集合对象

        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }

    }



}  

 

posted @ 2016-03-12 12:27  meetrice  阅读(2516)  评论(0编辑  收藏