Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected output with HashMap

CODE:

public class Puzzle23{
    void Puzzle23(){
        map1.put(String1, "1");
        map1.put(String2, "2");
    }

    private final NewMap map1 = new NewMap();
    private static final String String1 = new String("J2eeSig");
    private static final String String2 = new String("J2eeSig");

    public static void main(final String args[]){
        final Puzzle23 p22 = new Puzzle23();
        final Map<String, String> map2 = new HashMap();

        map2.put(String1, "1");
        map2.put(String2, "2");
        System.out.println(p22.map1.size() == map2.size() ? true : false);
        p22.map1.remove(new String(String1));
        map2.remove(new String(String2));
        System.out.println(p22.map1.size() == map2.size() ? true : false);
    }

    class NewMap extends IdentityHashMap<String, String>{
        public void put(final String... values){
            super.put(values[0], values[1]);
        }

        public int size(){
            return super.size() + 1 - 1 / 1 * 1;
        }
    }
}

Actual Result:-

false
true

Expected Result:-

true
true

Why???

like image 574
Sandhya Avatar asked Dec 14 '25 12:12

Sandhya


1 Answers

it's because of use NewMap is IdentityHashMap. Check documentation where is said

This class is not a general-purpose Map implementation! While this class implements the Map interface, it intentionally violates Map's general contract, which mandates the use of the equals method when comparing objects. This class is designed for use only in the rare cases wherein reference-equality semantics are required.

EDIT: Anyway I found a error in your code. void Puzzle23() is not constructor it's a method. Constructor have to be defined without return value (e.g. Puzzle23()). So you never fill map1. When you fix this you realize that your output is false false because of IdentityHashMap. When you switch map1 to HashMap output will be true true as you expected. Anyway check documentation of IdentityHashMap.

like image 184
michal.kreuzman Avatar answered Dec 17 '25 02:12

michal.kreuzman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!