Reputation: 261
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?
Upvotes: 0
Views: 8497
Reputation: 3519
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;
Upvotes: 0
Reputation: 3649
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);
}
}
Upvotes: 1
Reputation: 7919
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.
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 .
Upvotes: 0
Reputation: 17474
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`.
Upvotes: 0
Reputation: 27986
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";
Upvotes: 0
Reputation: 201527
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()
.
Upvotes: 2