开发者

Converting string types into integer types in Java

开发者 https://www.devze.com 2023-02-05 16:23 出处:网络
I know of this Integer.parseInt(args[0]); though in some other code I noticed this counts[(int) B.get(file,rank)]; where the (int) is supposedly converting the returned value from B.get into a Inte

I know of this

Integer.parseInt(args[0]);

though in some other code I noticed this counts[(int) B.get(file,rank)]; where the (int) is supposedly converting the returned value from B.get into a Integer.

I can understand the validity of 开发者_高级运维the Integer.parseInt statement, but where does the second one come from and is it proper Java code?


The second one is a cast; it doesn't turn one kind of object into another kind, but it allows you to change the form in which you are using the object.

Say I have an object of type Mammal but I happen to know that this particular instance is a Cat. I can do (Cat)myMammal and refer to the methods and properties that a Cat would have.

Needless to say this isn't a way to convert a string to an int. In the example you gave, you're taking an object of undetermined type (the output of get) and asserting that it's an int. This will only work if it really is an int.

If you want to convert a string to an int, you have to parse.


Integer.parseInt() takes a string and converts that to a int.

Using (int) is just a cast, which won't work with a string. Casting works by telling the compiler that you know the object you've got is already of that particular type. The compiler trusts, you - if you get this wrong you'll face a ClassCastException (though the compiler will moan at you if it works out that the cast can never work if the objects aren't part of the same inheritance hierarchy.)

In the case of primitives casting can be used to demote primitives from one type to another, so casting a double to an int works by dropping the decimal component.


IMHO, this is a non-sense, casting to Integer together with autoboxing would be fine, but I know no single case when this compiles without warning and without error.

final Map<String, Integer> m1 = new HashMap<String, Integer>();
m1.put("a", 42); // autoboxing
final int n = (int) m1.get(42); // WARNING: Unnecessary cast from Integer to int


final Map<String, Long> m2 = new HashMap<String, Long>();
m2.put("a", 43L); // autoboxing
final int n2 = (int) (long) m2.get(42); // fine
final int n2a = (int) m2.get(42); // ERROR: Cannot cast from Long to int

final Map<String, Object> m3 = new HashMap<String, Object>();
m3.put("a", 43); // autoboxing
final int n3 = (Integer) m3.get(42); // fine
final int n3a = (int) m3.get(42); // ERROR: Cannot cast from Object to int

Maybe it was a cast to Integer?

0

精彩评论

暂无评论...
验证码 换一张
取 消