HashSet with two equals object?

前端 未结 4 1311
礼貌的吻别
礼貌的吻别 2020-12-19 17:47

I created an object HashSet, and the value is an object (Triple) which is my own class. But I get a strange thing, when there are two equal objects on my HashSet, is it poss

4条回答
  •  清酒与你
    2020-12-19 18:23

    Looks like it returns true for Strings only...i tries to run the below code

                final HashSet carHashSet = new HashSet();
        final Car c1 = new  Car("black","ZX","deisel");
        final Car c2 = new  Car("black","ZX","deisel");
        carHashSet.add(c1);
    
        if (carHashSet.contains(c2))
            System.out.println("has c2 obj");
        else
            System.out.println("dont have C2 obj");
    
        final HashSet stringHashSet = new HashSet();
    
        final String k1 = "test";
        final String k2 = "test";//final String k2 = "Test";
    
        stringHashSet.add(k1);
    
        if (stringHashSet.contains(k2))
            System.out.println("has k2 obj");
        else
            System.out.println("dont have k2 obj");
    

    the output is as below:

    dont have C2 obj has k2 obj

    when i change k2 to final String k2 = "Test";, the output is

    dont have C2 obj dont have k2 obj

提交回复
热议问题