February 15, 2002
Q: This question seems easy, but nonetheless I have no idea how to do it. I have a byte array: a[100] . Is there a simple way to copy only from a[0] to byte a[50] ? (I don't want to use a for/while loop.)
A: You're correct, the answer is really simple. The problem is that the answer lies in one of those classes everyone seems to overlook: java.lang.System
. System
includes the following method that does what you need:
public static void arraycopy(Object src, int src_position, Object dst, int dst_position, int length)
So, to copy your array, try the following:
byte [] dst = new byte[50]; System.arraycopy( a, 0, dst, 0, 50 );
Java developers also overlook the java.util.Arrays
class. While Arrays
won't help you with your copy problem, it will help you sort and fill your arrays.
Learn more about this topic
- You'll find more in the java.lang.System Javadoc
http://java.sun.com/j2se/1.3/docs/api/java/lang/System.html - For more on arrays, read Tony's "Array of Arrays" (JavaWorld, December 1999)
http://www.javaworld.com/javaworld/javaqa/1999-12/01-qa-array.html - Want more? See the Java Q&A index page for the full Q&A catalog
http://www.javaworld.com/columns/jw-qna-index.shtml - For over 100 insightful Java tips from some of the best minds in the business, visit JavaWorld's Java Tips index page
http://www.javaworld.com/columns/jw-tips-index.shtml - Learn the basics of client-side Java in our Java Beginner discussion. Core topics include the Java language, the Java Virtual Machine, APIs, and development tools
http://forums.idg.net/webx?50@@.ee6b804 - Sign up for JavaWorld's free weekly Applied Java email newsletter
http://www.javaworld.com/subscribe - You'll find a wealth of IT-related articles from our sister publications at IDG.net