File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes How do you add to Arrays together? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How do you add to Arrays together?" Watch "How do you add to Arrays together?" New topic

How do you add to Arrays together?

Corbin Blake

Joined: Nov 10, 2004
Posts: 22
I want to take an array i.e. A[] and array B[] and add them together.

for instance if array A contains "abcd" and array B contains "efgh" i want to add them together and print out "abcdefgh".

Can you use arraycopy? I am at a lost for the logic to do so.
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
There may be a method in the Java API that will help with this, but you don't have to rely on that. In fact, it might take you less time to figure it out yourself. If you don't know where to start, why don't you write some ideas down on paper. Write out the steps that it will take to accomplish the task. Feel free to post your ideas here. This forum works very well for "thinking out loud", so to speak.



Java API Documentation
The Java Tutorial
Elouise Kivineva
Ranch Hand

Joined: Feb 07, 2002
Posts: 154
Corbin: By "adding together" do you mean that an array {a, b, c} added to
{b, c} would be {a, b, c, b, c} or just {a, b,c}?

I would simply find the length of each array and create a 3rd array of as long as the sum of the lengths of arrays 1 and 2.
Now iterate thru the indexes of the arrays 1 and 3 adding everything in array 1 to array 3.
Then iterate thru arrays 2 and 3 adding everything in array 2 to array 3. NOTE: You continue to fill the new array, you DO NOT overwrite what you already added.

If the new array is not supposed to have duplicates then you need to check for those when filling the new array or clean them out afterwards.

NOTE: If the things in these two arrays will aways be chars you could immediately create strings (using constructor) from the char arrays and just use the '+' function.
[ November 15, 2004: Message edited by: Elouise Kivineva ]
Maureen Charlton
Ranch Hand

Joined: Oct 04, 2004
Posts: 218
When the content of one array is to be copied into a second, they cannot simply be assigned to one another. For instance, the following statement will not copy contents of arrayA to arrayB i.e.

arrayB = arrayA;

If you try this in a program it will appear to work. But what actually happens is arrayB will reference the same memory as arrayA.

A new area of memory needs to be allocated for an additional array using the 'new' keywork, arrayB will then reference this. The contents of arrayA is then copied into arrayB by using a loop.

Example code:
I agree. Here's the link:
subject: How do you add to Arrays together?
It's not a secret anymore!