zoukankan      html  css  js  c++  java
  • 一个工具类Pair的实现

    Pair类常用,基础类库中也有提供,但是都没有包括HashCode和Equals的处理,恰好需要用,便写了一个,代码如下,HashCode的地方有些拿不准,欢迎大家拍砖!

    public class Pair
    {
        
    // Fields
        public object First;
        
    public object Second;

        
    // Methods
        public Pair()
        
    {
        }


        
    public Pair(object first, object second)
        
    {
            
    this.First = first;
            
    this.Second = second;
        }


        
    public override int GetHashCode()
        
    {
            
    if (First == null)
            
    {
                
    return Second != null ? Second.GetHashCode() : 0;
            }
     else 
            
    {
                
    if (Second == null)
                
    {
                    
    return First.GetHashCode();
                }

                
    else
                
    {
                    
    long temp = First.GetHashCode() + Second.GetHashCode();

                    
    //这里有些拿不准,参考JDK Long的实现的,但JDK中使用的无符号有移运算符>>>
                    return (int)(temp ^ (temp >> 32)); 
                }

            }

        }


        
    public override bool Equals(object obj)
        
    {
            Pair cmpVal 
    = obj as Pair;

            
    if (cmpVal == null)
            
    {
                
    return false;
            }


            
    if (this.First != null)
            
    {
                
    if (!this.First.Equals(cmpVal.First))
                
    {
                    
    return false;
                }

            }

            
    else
            
    {
                
    if (cmpVal.First != null)
                
    {
                    
    return false;
                }

            }


            
    if (this.Second != null)
            
    {
                
    return this.Second.Equals(cmpVal.Second);
            }

            
    else
            
    {
                
    return cmpVal.Second == null;
            }

        }


        
    public static bool operator ==(Pair lhs, Pair rhs)
        
    {
            
    if (lhs != null)
            
    {
                
    return lhs.Equals(rhs);
            }


            
    return rhs == null;
        }


        
    public static bool operator !=(Pair lhs, Pair rhs)
        
    {
            
    if (lhs != null)
            
    {
                
    return !lhs.Equals(rhs);
            }


            
    return rhs != null;
        }

    }
  • 相关阅读:
    软件测试作业随笔之二:Homework 2
    软件项目管理作业随笔之一:记我完成的一个项目
    C#博客随笔之十:Problem Statement+System Glossary+System Supplementary Specification FOR每美欲下
    C#博客随笔之九:EF框架的使用
    C#博客随笔之八:EntityFramework初识
    C#博客随笔之七:反射初体验
    C#博客随笔之六:数据绑定
    node.js 框架基本功能
    为什么不用第三方缓存
    微服务基础设施实现方案 -- node.js
  • 原文地址:https://www.cnblogs.com/jobs/p/25696.html
Copyright © 2011-2022 走看看