Why do people still use primitive types in Java?

后端 未结 21 2494
暗喜
暗喜 2020-11-22 15:11

Since Java 5, we\'ve had boxing/unboxing of primitive types so that int is wrapped to be java.lang.Integer, and so and and so forth.

I see

21条回答
  •  耶瑟儿~
    2020-11-22 15:39

    Because JAVA performs all mathematical operations in primitive types. Consider this example:

    public static int sumEven(List li) {
        int sum = 0;
        for (Integer i: li)
            if (i % 2 == 0)
                sum += i;
            return sum;
    }
    

    Here, reminder and unary plus operations can not be applied on Integer(Reference) type, compiler performs unboxing and do the operations.

    So, make sure how many autoboxing and unboxing operations happen in java program. Since, It takes time to perform this operations.

    Generally, it is better to keep arguments of type Reference and result of primitive type.

提交回复
热议问题