sky_handsome's profile天意PhotosBlogLists Tools Help

Blog


    September 14

    公布4月17日博客答案

    首先,这不是因为多次添加同一个key造成的,否则他应该抛出另外的异常而不是NullPointerException。不信的话,你可以加一个if (!dict.Contains(key))在外面,他同样会fail。
    真正的原因是需要掌握Dictionary作为一个Hash Table背后的原理。对于任意一个key,首先key.GetHashCode() will be called.然后,由此hash code来决定该key应该放入数组的哪个bucket。由于bucket是远小于key的hash code的范围的,因此hash code和bucket通常使用一个多对一的函数。当程序运行一段后,碰巧你的随机数产生的hash code被函数映射到同一个bucket,这个时候为了决定你插入的key是否和之前被分配到同一个bucket的key一样,这是Equals()会被调用。而明显的,Equals()里面的key.s是Null.因此NullPointerException被抛出。其实这也是为什么教科书上都说,当你override GetHashCode的时候,最好override Equals。这实际上是需要你明白你在干什么。

    Comments

    Please wait...
    Sorry, the comment you entered is too long. Please shorten it.
    You didn't enter anything. Please try again.
    Sorry, we can't add your comment right now. Please try again later.
    To add a comment, you need permission from your parent. Ask for permission
    Your parent has turned off comments.
    Sorry, we can't delete your comment right now. Please try again later.
    You've exceeded the maximum number of comments that can be left in one day. Please try again in 24 hours.
    Your account has had the ability to leave comments disabled because our systems indicate that you may be spamming other users. If you believe that your account has been disabled in error please contact Windows Live support.
    Complete the security check below to finish leaving your comment.
    The characters you type in the security check must match the characters in the picture or audio.

    To add a comment, sign in with your Windows Live ID (if you use Hotmail, Messenger, or Xbox LIVE, you have a Windows Live ID). Sign in


    Don't have a Windows Live ID? Sign up

    Trackbacks

    The trackback URL for this entry is:
    http://sky1983121.spaces.live.com/blog/cns!2E93CC4DC32FC730!956.trak
    Weblogs that reference this entry
    • None