How to find last non-empty index in an array - java

I am using an input file to populate my array with different strings. how do I check up to where the array is filled? I initialize the size of my array to 30000, but how do I check up to which index it contains a string?
Thank you for your help!

Low-level approach: while populating the array, maintain a count variable, adding 1 to it on every element you insert into the array.
Professional approach: instead of an array, use a java.util.List, e.g. a java.util.ArrayList. List instances do the counting for you (and by the way, don't waste 25000 empty elements if your file only contains 5000).

Related

Insertion at the end of a linked list is not a special case. So what about the end of an array?

So, I was reading my textbook about linked lists. So if it isn't a special case if something is inserted at the end of a linked list, is it a special case, by way of contrast if an element is inserted at the end of an array? What is the reason behind the answer. Why? Why isn't it a special case when inserted at the end of a link list and why is/isn't a special case at the end of an array? What about for ArrayLists?
It is also not a special case for Array (if we are not talking about exceeding bounds of Array). But for ArrayList it could be a special case, because ArrayList has a capacity and if it is exceded ArrayList needs to be resized in order to make sure that it has space for inserted element.
Arrays have a fixed size that you give at initialization (This part is important because array elements are stored at consecutive memory addresses). Hence, you cannot append an element to an array without creating a new array.
int[] myArray = new int[10];
myArray.append(42); //Where should it be stored? It would not make sense.
For lists, it depends on the list implementation. The LinkedList consists of several Node connected to each other. Hence, adding an element to the end of the list is equivalent to connecting a new Node to the last Node of the list.

ArrayList/LinkedList get First Index number

Is is possible to get out of an ArrayList the first number of the first index?
Here's an Example:
In there are 5 items:
path = {0.5,5.0},{0.6,6.0},{0.7,7.0},{0.8,8.0},{0.9,9.0}
And I want to get the number 5.0 out of {0.5,5.0}...
I tried it with path.get(0) But it only gives me {0.5,5.0} back.
Is it possible to get 5.0 out of it without getting all the other numbers?
If your ArrayList contains arrays, this is the way to go
myList.get(0)[1] // You're getting the index 1 from the 1st array of your ArrayList
Otherwise, if it is containing other ArrayList's
myList.get(0).get(1) // Same logic as above applied to the Collection
If your curly braces in the ArrayList are actually brackets (they probably are), you can use:
myArray.get(0)[index] to get the index you want. In your example it is:
myArray.get(0)[1];
Note: if your ArrayList elements are also ArrayList then you need to use get(0).get(1) instead of get(0)[1].

Adding a value to the middle of an array without replacing an existing value in java

I am researching the difference of arrays and Arraylists. Can anyone clarify if it is possible to add an element to the middle of an array without replacing the existing value (like what the x.add() would to for an arraylist)?
For example: if I had an array of fruit [apples, pears, peaches, nectarines] and I want to insert plums [apples, pears, plums, peaches, nectarines]. Would this be possible and how would it be done?
An array size is fixed, so normally it's complicated to add an element into an array.
But in special cases it is possible:
It is only possible if the array is not yet fully filled.
Like [apples, pears, peaches, nectarines, NULL, NULL]
inserting is then possible if the current size, which you have to record on a separate place, is smaller than the array size.
Inserting then works using System.arraycopy(), where you first move all elements at inserting position and above to one position to the right. Then you add the new element.
The result would be [apples, pears, plums, peaches, nectarines, NULL]
leaving yet place for one more element.
Java's ArrayList uses this technic to provide a dynamic growing array.
In most cases it's better to use ArrayList for this task. In special cases where you have to read millions of elements such a self managed "growing" array is much more memory efficient (e.g 4 times less the memory, because ArrayList always uses Objects while array could also use primitive types, and they need less memory).
Note:
If one reads you question puristic the answer is "No", because you showed a fully filled array. The only chance to add any more element is to allocate a new array with bigger size and copy the old elements and the new one. But then you have a new array. The access to that array must be encapsulated that no one can reference it, except the class which manages the adding and getting values from it. Just look at the source code of ArrayList to get an Idea.
No, it's not possible.
You would need to allocate a new array larger than the existing one and copy everything over to it in the new positions.
No. Arrays have fixed length, and cannot be resized.
An array is a continuous region of memory - so no, you cannot add an element in the middle of an existing array. ArrayList is a List backed by an array. When necessary, ArrayList will allocate a new array and copy existing values into the newly allocate array.
392 public void add(int index, E element) {
393 rangeCheckForAdd(index);
394
395 ensureCapacity(size+1); // Increments modCount!!
396 System.arraycopy(elementData, index, elementData, index + 1,
397 size - index);
398 elementData[index] = element;
399 size++;
400 }
Read the code for ArrayList here.
const array = [1,2,3];
array.splice(2,0,5); \\ (index, number of items you want to replace, item to be replaced with separated by commas)
console.log(array); \\ [1,5,3]
array2 = [1,2,3];
array2.splice(1,0,4,5);
console.log(array2); \\ [1, 4, 5, 2, 3]
Hope this helps the JS Devs

Remove element from Array Java

I am currently making a tiny little program that should be able to select a random element i put into the array using a Random of course (For practice purposes) and when a element in the array has been chosen at random. i want to remove this element in the array, so how do you remove a element in a array the easiest way?
Its the only thing i want to know. I got everything else sorted. It's just removing the element it has chosen (the random takes a random number between 0 and the amount of elements in the array, so if it chooses 0, it will take the first element in the array, and so on)
You can use ArrayList which support remove or add function, which actually is an resizable array.
You can't remove an element from an array. You can replace it with some other value that indicates "nothing", null for example.
An easy solution is to convert the array into a list.
list = Arrays.asList(array);
Remove any element from the list and then revert it back to an array using
array = list.toArray();
Hope it helps.
Use List instead of Array, and if you want to stay on Array than there is 2 solution,
Create another Array ignoring your element which you want to delete.
create a List using Array.asList(...) than remove element from list and convert back to Array.
but according to me its better for you as well as java to use List. because List provide a many build-in functions.

adding to the middle of an empty ArrayList?

if I create a new arraylist of size 5...
Player P;
ArrayList<Player> orderedPlayers = new ArrayList<Player>(5);
and then I try to add to the middle of that arraylist...
orderedPlayers.add(2, P);
I get an indexoutofbounds... I also get indexoutofbounds if I use set instead of add...
orderedPlayers.set(2, P);
in fact the only way I can add P to the arraylist is if I use the 0 index...
orderedPlayers.add(0, P);
and also for some strange reason when I do that my debugger in eclipse sees that element added to the 4th index of orderedPlayers instead of the 0th... is ArrayList buggy or am I completely missing something? how would I add to the middle of a null ArrayList?
The 5 is the initial capacity, not the actual size. You can't add to the middle of an empty array list.
Here is probably what you want to do in order to initialize orderedPlayers:
ArrayList<Player> orderedPlayers =
new ArrayList<Player>(Collections.nCopies( 5, null ));
Then you have a list with 5 null elements, at this point you can insert in the middle of it.
When you create an ArrayList with a number in parameter, this number will be used to set the initial capacity. That way the List won't need to create a new array for "every" call to add(). If you can tell that your List will contain 100 elements, you can use new ArrayList(100). That doesn't mean that the 100 elements exists or are accessible.
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically. The details of the growth policy are not specified beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large number of elements using the ensureCapacity operation. This may reduce the amount of incremental reallocation.
ArrayLists are dynamic structures... if you want to be able to add stuff at specific locations, you might have to use an array instead.
you may initialize your array list by NULL objects in a loop.
or even if the size is fixed. then use Array instead of List.
You seem to be under the mistaken impression that when you write new ArrayList<Player>(5), you're getting something similar to a 5-element array. You aren't. You're getting an empty list that happens to be backed by an internal array that can initially hold up to 5 elements. The list itself, however, has no elements at all.
Lists are dynamic and grow and shrink as elements are added to them and removed from them. You start out with 0 elements. If you then add 5 players, the list will have 5 elements. If you just use the normal add(T) method with no index, you'll end up with the elements in the order they were added.
By constructing an ArrayList with an initial capacity ArrayList(int initialCapacity), you are indicating roughly how large the list can get before Java will increase its size.
You are not allocating slots, as in an array. The ArrayList's size is based on the number of elements in the list, and you cannot insert or set a value to an index greater than its size.

Categories

Resources