-5

可能重复:
字符串对象的哈希码

嗨,我是 java 编程新手,我想创建多个 Myclass 的 obj,为此编写了下面的代码。为什么它会生成相同的对象

class Myclass {

        private static Myclass single;
        private Myclass() {

        }
        public static synchronized Myclass obj() {
            if (single == null) {
                single = new Myclass();
            }
            return single;
        }
    }
    public class Demo {
        public static void main(String args[]) {
            Myclass obj = Myclass.obj();
            System.out.println("one  "+obj);
            Myclass obj1 = Myclass.obj();
            System.out.println("two  "+obj1);
        }
    }
4

2 回答 2

1

You're explicitly designing MyClass.obj() to return a singleton, so you shouldn't be suprised that is returns the same instance - so both references point to the same object and have the same hashcode.

于 2012-05-16T09:23:47.890 回答
1

实际上是单个实例,两者都是同一个对象

于 2012-05-16T09:21:28.783 回答