0

Suppose I have a two dimensional array, e.g. String array[][] = {{"",""},{"",""}} and this array prints out each row in a new line.

Now, my question is, if a user wants to add to this array with a new set of rows via a Scanner input how do I go about doing that?

For example, suppose I have a list of inventory and I just noticed a new shipment arrived. How do I add this new inventory to the existing inventory.

What I was thinking was, if my array isn't large enough, then I would have to make a new, bigger array and copy the original data there. From this point, I can add the new data. So I was thinking a couple of for loops should suffice. But I don't know how to apply it here?

4
  • 3
    Java arrays aren't dynamically sized... so use a List. Commented Feb 5, 2015 at 5:02
  • @ElliottFrisch Can you elaborate please? Commented Feb 5, 2015 at 5:08
  • You can't add to an array, their size is fixed. If you want the number of things in the collection to change you need to use a different structure like an implementation of List. Commented Feb 5, 2015 at 5:14
  • have a look at this stackoverflow.com/questions/10487104/… Commented Feb 5, 2015 at 5:14

6 Answers 6

2

Since Java arrays are not dynamically sized data structures, I suggest you use a Collection (like List) which is (an interface type representing a dynamically sized data structure). Something like,

List<List<String>> al = new ArrayList<>();
al.add(Arrays.asList("1", "2"));
al.add(Arrays.asList("3", "4"));
String str = "5, 6"; // <-- let's assume the user wants to add a 5 and 6
al.add(Arrays.asList(str.split(",\\s*")));
System.out.println(al);

Output is

[[1, 2], [3, 4], [5, 6]]

Note that unlike arrays, ArrayList and LinkedList both override toString().

Sign up to request clarification or add additional context in comments.

2 Comments

Hm, what I was thinking was, if my array isn't large enough, then I would have to make a new, bigger array and copy the original data there. From this point, I can add the new data. So I was thinking a couple of for loops should suffice. But I don't know how to apply it here?
Use the answer provided by @sprinter below if you want an implementation of that sort... note that your approach will involve modifying the array reference on every addition.
1

Yes you can increase the size of an array by calling Arrays.copyOf method and then reassigning it to initial object. But anyhow if you don't want to go through copying again and again ArrayList is a better choice since it internally uses Arrays.copyOf to increase the size of Array as it internally does it when you call add(E e) as:

public boolean add(E e) {
    ensureCapacityInternal(size + 1);  // Increments modCount!!
    elementData[size++] = e;
    return true;
}

ensureCapacityInternal(size + 1) checks for the max of Default capacity allocated i.e. 10 to size+1 as:

private void ensureCapacityInternal(int minCapacity) {
    if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
        minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
    }
    ensureExplicitCapacity(minCapacity);
}

If the capacity exceeds ensureExplicitCapacity(minCapacity); is called which increases the capacity of transient Object[] by calling grow() which internally does Arrays.copyOf. Hope this explanation helps.

For your problem you can perform it as:

String array[][] = { { "hello", "how" }, { "are", "you" } };
Scanner scan = null;
String str = null;
int len = array.length;
int i = 0;
while (i != 6) { // provide the loop as you require
    scan = new Scanner(new InputStreamReader(System.in));
    str = scan.next();
    try {
        array[len][1] = str; // will try to add to second position. If array is out of index an exception will be thrown
        len++; // won't increase if exception is thrown 
    } catch (ArrayIndexOutOfBoundsException e) {
        array = Arrays.copyOf(array, len + 1); // copying the array
        array[len] = new String[2]; // creating and assigning string array to new row else it will be null
        array[len][0] = str; // adding new string to new array position
    }
    i++;
}
scan.close();

for (String[] strings : array) {
    for (String string : strings) {
        System.out.println(string);
    }
}

2 Comments

Can you elaborate on the arrays.copyof? What I was thinking was, if my array isn't large enough, then I would have to make a new, bigger array and copy the original data there. From this point, I can add the new data. So I was thinking a couple of for loops should suffice. But I don't know how to apply it here?
@Robben edited the answer with solution of the scenario.
0

You cannot expand an array in place - it needs to be copied to a new array. Fortunately there is a method to make this easy for you: Arrays.copyOf.

So:

String[] names = {"Bill", "Bob"};
names = Arrays.copyOf(names, names.length + 1);
names[names.length - 1] = "Mary";

Comments

0

Arrays are fixed size. You cannot change the size unless you create a new array each time.

A proper way will be using ArrayList.

List<String> shipments = new ArrayList<String>();
shipments.add("newShipments");

I see that you have more that one attribute in your records. You can create a Shipment class. (If you have more than one string or variable needed in your record, you can create an arraylist of objects as follows:)

Example:

class Shipment
{
    //Place your attributes here..
    String name;
    String id;

    //Constructors and methods not shown
}

List<Shipment> records = new ArrayList<Shipment>();
records.add(new Shipment("Dresses", "A-123"));

//Having an arraylist of objects allows you to hold more than 1 variable.
//Now each `records` can hold 2 String variables `name` and `id`.

Comments

0

Case 1:Using Array

Suppose

String array[][] = {{"oldinventory1","oldinventory2"},{"oldinventory3","oldinventory4"}};

and you want new inventory to be inserted at a2 you do

array[2][2]="newinventory1";

It wiil give an array index out of bound as there is no a2 index in array because array row and col are fixed in the first.

ARRAY DEMO

Case 2:Using List

You can remove arraysize problem by using List.And there is also one more advantage by declaring List inside List as given in example by @Elliott Frisch

         List<List<String>> al = new ArrayList<>();
         al.add(Arrays.asList("oldinventory1", "oldinventory2"));
         al.add(Arrays.asList("oldinventory3", "oldinventory4"));
         String str = "newinventory5, newinventory6,, newinventory6";

i.e not only we can increase the row dynamically but also we can add new column.So if inventory increase at any time you say from 3 to 5 or to 1 you can handle easily .

LIST DEMO

4 Comments

Hm, what I was thinking was, if my array isn't large enough, then I would have to make a new, bigger array and copy the original data there. From this point, I can add the new data. So I was thinking a couple of for loops should suffice. But I don't know how to apply it here?
@Robben is the new array have fixed inputs means the shipment have any limit or not.
We can place a limit to 10 columns where as the rows have no limit. So array[][10].
@Robben check ideone.com/xYLTXx I have fixed the size to a[][2] you can change it by setting maxcol
0

The size of arrays are fixed, so you need to copy the array to a bigger one. You can use Arrays.copyOf() to make the copy.

This is an example of use of the copyOf method with a multidimensional array.

    String[][] array = {{"A", "B"},{"C", "D"}};
    String[] newValuesArray = {"E", "F"};
    array = Arrays.copyOf(array, array.length + 1);
    array[array.length - 1] = newValuesArray;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.