davigueras
davigueras

Reputation: 195

Casting a double result from a divison into an int in Java

I want to use a method that requires an int. This int is determined by a division potentially solved as a double. I need to perform this as neat and short as possible and I am wondering if I can count that the method will take the double directly casted as int and if this means a single truncation with no roundings.

Do I have to necessarily use Math static methods?
Could this give errors for non int parameter entries to subList?
Could someone provide any guidance about this?

List<Integer> b = null;
List<Integer> c = null;
int size = a.size();

b.addAll(a.subList(0, size / 2)); // To hold the first half
c.addAll(a.subList(size / 2, size)); // To hold the second half [and excess]

Thank you in advance for your help.

Upvotes: 1

Views: 267

Answers (2)

No Idea For Name
No Idea For Name

Reputation: 11597

it will take the double casted to integer and will not round it, just disregard everything after the "."

so if the division of 9.8/2 is 4.9 then you'll get 4 for doing

int x = 9.8/2;

you don't need to use the Math static methods for devision and you won't get errors for the code you gave

to conclude, you can just run your code and see if the result is as you want it.

b.addAll(a.subList(0, size / 2));

should run without problem

Upvotes: 1

AlexR
AlexR

Reputation: 115388

What's wrong with b.addAll(a.subList(0, (int)(size / 2)));?

Upvotes: 0

Related Questions