-2

Is there a way to add new items into this array?

            RowMsg RowMsg_data[] = new RowMsg[] {

                    new RowMsg(R.drawable.ic_launcher, "Message 1"),
                    new RowMsg(R.drawable.ic_launcher, "Message 2"),
                    new RowMsg(R.drawable.ic_launcher, "Message 3"),
                    new RowMsg(R.drawable.ic_launcher, "Message 4")

            };

            // here i want add next one element, for example: RowMsg(R.drawable.ic_launcher, "Message 5")

5 Answers5

3

No. You can't add elements to arrays - once you've created the array, its size can't change.

You'd be better off with a list:

List<RowMsg> messages = new ArrayList<RowMsg>();
messages.add(new RowMsg(R.drawable.ic_launcher, "Message 1"));
// etc

As an aside, it's more conventional to keep the type information all in one place, and Java variables are conventionally camel-cased - so even if you did stick with your array, it would be better to declare it as:

RowMsg[] rowMsgData = new RowMsg[] {
    ...
};

(I'd also suggest avoiding abbreviations, but there we go.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
1

If you really need RowMsg_data to be an array do

RowMsg_data = new ArrayList<RowMsg>(Arrays.asList(RowMsg_data))
               .add(new RowMsg(R.drawable.ic_launcher, "Message 5"))
               .toArray();
user000001
  • 32,226
  • 12
  • 81
  • 108
0

If you use an ArrayList, then you won't have to re-allocate another bigger array and copy from your first array, that is all handled by ArrayList.

Here's the documentation for ArrayList.

rgettman
  • 176,041
  • 30
  • 275
  • 357
0

You cannot change the size of an array after initalization. Use a List e.g. ArrayList<RowMsg> instead.

Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
MrSmith42
  • 9,961
  • 6
  • 38
  • 49
0

try

    RowMsg_data = Arrays.copyOf(RowMsg_data, RowMsg_data.length);
    RowMsg_data[RowMsg_data - 1] = new RowMsg(R.drawable.ic_launcher, "Message 5");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275