Java implementation converts object type to int type

Time:2021-9-25

How to convert object type to int type


Object object = null;
try
{
    Integer.parseInt(object.toString());
}
catch (NumberFormatException e)
{}

You can also determine whether it is an integer first

//You can determine whether it is an integer first
Object object = "111";
if (object instanceof Integer) {
   Integer.parseInt(object.toString());
}

String converts the pit encountered by integer

In the project development, interger is used to convert the string to integer type, and the corresponding comparison is made. The initial data is small, and no problems are found, such as 15


String a = "15";
System.out.println(Integer.valueOf(a) == Integer.valueOf("15"));

The returned result is true, but give me 423


String a = "423";
System.out.println(Integer.valueOf(a) == Integer.valueOf("423"));

The returned result is false. Immediately check the source code of integer and find the following code


public static Integer valueOf(int i) {     
      final int offset = 128;     
      if (i >= -128 && i <= 127) { // must cache      
        return IntegerCache.cache[i + offset];     
     }     
     return new Integer(i);     
} 

It is found that the JDK does not cache the data from – 128 to 127. If the number is within this range, it will not start a new integer. I see. When it is 423, two objects will be created, and we use the = = comparison address character, so it must be different.

We can check the memory address. 15 memory address

Address of 423

The memory address of 423 is different. So we need to use equals for comparison, not = = for comparison

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer.

Recommended Today

A detailed explanation of the differences between Perl and strawberry Perl and ActivePerl

Perl is the abbreviation of practical extraction and report language “practical report extraction language”. Application of activestateperl and strawberry PERL on Windows platformcompiler。 Perl   The relationship between the latter two is that C language and Linux system have their own GCC. The biggest difference between activestate Perl and strawberry Perl is that strawberry Perl […]