Logo 
Search:

Java Answers

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds
  Question Asked By: James Rivera   on Jul 31 In Java Category.

  
Question Answered By: Jake Williams   on Jul 31

First a question. Are you sure the stuff is getting into "a" in the first
place? From what you've given here, you've never created an array for "a" to
point at. Somewhere there needs to be an "a = new byte [nn];" to create the
actual array.

Second, you can't increase the size of an array. (You may already know this,
it's not clear from what you've said.) You have to create a new array and dump
the old one.

Next

byte c[a.length + 1];

should be

byte c[] = new byte [a.length + 1];

Then

c = a;

undoes the good work. It dumps the new array you just created and puts a
reference to the same array that "a" is referencing into "c". I.e. "a" and "c"
are now pointing to the first array. The new array no longer has a reference
and will be discarded.

To copy an array into a different-sized area, you need to use a "for" loop or

System.arraycopy (a, 0, c, 0, a.length);

Now

c[a.length + 1] = b;

is wrong too. The indexes of "a" run from a[0] to a[length-1]. The next
position in "c" is c[a.length].

Finally, you probably want the extended array back in "a". Here you can use

a = c;

to achieve what you want.

So, a little test program

byte[] a = new byte[3];
a[0] = 1;
a[1] = 2;
a[2] = 3;
byte[] c = new byte[a.length+1];
System.arraycopy (a, 0, c, 0, a.length);
c[a.length] = 4;
a = c;
for (int i = 0; i < a.length; i++)
System.out.println (a[i]);


demonstrates that "a" now has four items in it.

Share: 

 

This Question has 28 more answer(s). View Complete Question Thread

 
Didn't find what you were looking for? Find more on Why we declare the constructor private? Or get search suggestion and latest updates.


Tagged: