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;
        }

    }
  • 相关阅读:
    基础算法:求目标值 &字符串反转
    算法计算出股票最佳交易时间点
    Python 设计模式—命令模式
    Python 设计模式—代理模式
    有趣的算法题~单调栈
    令人头大的字符串—算法处理
    WebUI 自动化测试的经典设计模式:PO
    双指针—滑动窗口算法解析
    Python 设计模式—观察者模式
    多线程之读写锁原理
  • 原文地址:https://www.cnblogs.com/jobs/p/25696.html
Copyright © 2011-2022 走看看