Discuss / Java / 交作业了

交作业了

Topic source

勿忘我

#1 Created at ... [Delete] [Delete and Lock User]
public class StaticFieldAndMethod {    
    public static void main(String[] args) {        
        int cycleCount = 10000;
        for (int i = 1; i <= cycleCount; i++) {            
            new Human((i % 2 == 0 ? GENDER.MALE : GENDER.FEMALE), (int) (Math.random() * 100), "二狗子");
        }        
        System.out.println(Human.getInstancesCount());
    }
}

class Human {
    
    private static final AtomicInteger INSTANCE_COUNT = new AtomicInteger(0);

    private final GENDER gender;

    private final Integer age;

    private final String name;

    public static int getInstancesCount() {        
        return INSTANCE_COUNT.get();
    }    

    public Human(GENDER gender, int age, String name) {        
        this.gender = gender;
        this.age = age;
        this.name = name;
        INSTANCE_COUNT.incrementAndGet();
    }
}

enum GENDER {    
     MALE,
     FEMALE
}

  • 1

Reply