Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Double array to int array?

 
Jody Monahan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,

I was just wondering is there any way to convert a double array to an integer array?

Thanks in advance,
Jody
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just with a loop:

>
 
Jelle Klap
Bartender
Posts: 1951
7
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Casting is obviously not an option, so that leaves iterating the source array, casting the element at every iteration and storing it in the destination array of the desired component type.
Unfortunately System.arraycopy() won't help you here and neither will any of the utility methods provided by the java.util.Arrays class, so you'll have to do code the loop-convert-store routine yourself.

Edit: Sloooooooow.
 
Rory Evans
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest Friedman-Hill wrote:Just with a loop:

>


In the above code, shouldn't it read

Otherwise, the loop will start with element 1 of the array rather than element 0.
 
Rob Spoor
Sheriff
Pie
Posts: 20511
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, the ++i will still be executed after all other code in the loop body has executed.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not that it matters too much most of the time, but you should always use ++i, not i++, in loops like this, because i++ implies just a tiny bit more work for the computer. ++i means "add one to the variable, and use the result", while i++ means "make a copy of the variable, increment the variable, and use the copy." In a very tight loop, making that copy can make a measurable difference (except when the vm is smart enough to realize the copy isn't needed, and optimizes it away.)
 
Jody Monahan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cheers everyone, thanks for all of the replies!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic