Adding element to Java array - java

How can I add an element to an array while expanding the length of the array by one unit without using ArrayList? I'm a student, and it's forbidden for the assignment.
I have written a method that does it (sort of). It increments the array length every time its called but it only saves the last input parameter tot the very last element (every other element is made null when I create the new array with new length). The method is called in my constructor that makes an instance of an object from every line scanned in a text file, and I am supposed to add this line to an instance array.

You can't.
You can only create a new array which is longer than the old one. Other references of your program, already having a reference to the old array, are not affected and keep the old sized array.

Related

Java array vs Array

It's been a while since I took a proper course on Java and I'm hoping someone can confirm/correct my understanding.
Consider the variables int[] arr and ArrayList arrLi:
arr has pointers directly to each component. arr[3] goes directly to the fourth element whereas arrLi.get(3) would have to traverse through the first three elements to get to the fourth.
Reassigning a component, such as a[3] = 0, does not rewrite the entire array.
Each time you want to add an element to arr, you would need to rewrite the entire array. For example, if there are 100 elements in arr, you have to make a new array with size 101 and copy all the elements from arr then add the new one. If you later decide to add yet another element, you'd have to go through the whole process again to add the 102-nd element.
arrLi adds (to end, front, or middle) and removes elements very efficiently because all it does is add/remove nodes and adjust the links.
ArrayList is a resizable array implementation of the List interface. Therefore fetching an element does not require traversing the previous elements.
Rewriting a value does not require rewriting the entire array in either case.
Yes, an array does need to be recreated if you need more space.
While it is called a list, ArrayList internally behaves much more like an array. ArrayList sometimes needs to be resized, meaning the underlying array needs to be recreated. However, this happens infrequently enough to not affect the average performance of an ArrayList over an array by much.
Please refer to https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html for more information

Lookup of a number in an array

I wanted to ask what am I doing wrong that is causing the if statement to be false every time I run the program. I've also tried to use .equals(num) instead of the Array.asList(num) to check if the value is in there, but that caused the for loop to repeat the "Not in database" multiple times.
Arrays.asList(Data) creates a list whose only element is an array of int (i.e. List<int[]>). That's why Arrays.asList(Data).contains(num)) always returns false.
Try changing your array to :
Integer Data[] = new Integer[n];
This will make Arrays.asList(Data) create a list of Integer (List<Integer>) containing all the integers of the original array, which is what you need.
The reason for this behavior is the Arrays.asList expects one or more Objects as its input. If you pass an array of Objects (such as Integer[]), it is equivalent to passing multiple Objects. If, however, you pass an array of primitives (such as int[]), the only Object in your input is the array itself, so Arrays.asList() creates a list whose only element is that array.

More efficient for an Java Array

I have an assignment, in which we have to create a directory which stores names and an extension number. In the first part we have to store the information in just an Array. We have to be able to add an entry to the Array and also initially read a .txt file and store it in the Array. Finally it has to print the Array. I was just wondering what would be more efficient because I only started learning code the last few months and this is difficult for me.
1) Would it be better to first create an Array of size [9999] (because that is the max number of entries the directory could have because everyone has a unique four digit number). I have an INT called count which keeps a count of what the last Array[x] to be added so when I call a method like addEntry, it will add the Entry to [X+1].
The problems with this be is that from what I have read, Arrays are huge and it could have performance problems. Also I have to be able to make a 'lookup' method which should be able to search the Array for someones number by entering their name.
My other option:
2) When the file is read, it counts how many lines the file has (each entry will be on its own line) then creates an Array of the number of lines in the text file. Whenever I want to add a new Entry, I copy the Array into an ArrayList, then back to an Array with the new Entry added. However I also read that copying arrays is not so good too and in a realistic view, if someone was to use this directory they could be adding entries every day.
Aslong as I store in an Array and print the Array into a table it is all good, but what would be the best way to make the actual Array when you don't know the size? (Yes I know I can use ArrayList but its specifically said not to)
Also how would you go about deleting an Entry in the Array, if I use my way there would be a missing entry at Array[x] where x got deleted.
Thanks in advance for any replies.
It is best to initialize an array to the size that you initially need it. When you need to add items to the array after that, you can uses a memory copy rather than an object clone.
int[] arrayOne = new int[20];
int[] arrayTwo = new int[40];
System.arraycopy(arrayOne, 0, arrayTwo, 0, arrayOne.length);
This copy is actually very fast because it just makes a direct copy from memory. This is actually what the underlying code of array list does when it doubles in size.
If you want a "dynamic" sized array, you could write your own version of array list.
For example:
Starts at size 1
Doubles in size when it gets full
shifts objects on a delete using System.arraycopy()
reduces in half when a delete causes size to be less than n/3

Re initialize a string array with no more memory left

In Java, since strings are immutable, when we re assign a string Array element to a different string and are out of memory would it compile and run fine?
my understanding is for example if there are 2 elements in a string array, "John" and "Henry", when i change the array's second element to "Tom", what happens to "Henry" since it cant be really over written (immutable strings) and behind the scenes is java pointing to a new location (should array locations not be next to each other? ).
I ran a test and it successfully changed the second element to Tom. It compiled and ran fine. As per my understanding this should not have been allowed because strings cant be over written and array are supposed to be consecutive memory locations. please clarify - thanks
Each cell of your array contains the address of a String instance. When you change the value of the second cell it just points to another String instance, and if the instance previously pointed by that cell is no longer pointed by any other variable, might be chosen for garbage collection.

How do I make an array from inputted information (i.e. names) and then use it as objects within the code?

I've been reading up on it, but every question I've found has asked for slightly different things, such as only wanting a single letter for their array, or in a different language (I'm new and only learning java at the moment), so here I am.
I want to set up an array that uses the user's input for their names.
What I have so far is this, I'm assuming this is the declaration line, where later I use an input line to define a value within the array (which I also am unsure how to do)
String[] array = {"name"};
But I don't know how to for example print.out the object or keep up with which name will be what value. I appreciate your time taken to teach me!
EDIT for further clarification. I'm trying to write up a small app that asks the user for numerous names, addresses, and phone numbers (Type name -> Type name's address -> type name's phone number, ask if they want to add another person, if yes then go back to asking for another name)
I am unsure how to set up a String array or how to use it throughout. However, thanks to your input and coming back after some fresh air, I have a better idea how to word it for google. Thank you guys for your help, even if it was just to gesture a better articulated question.
An array is a sequence of values. You have created an array of Strings that is one String long. To access the value at a specific of an array, use array subscript notation: the name of the array followed by a pair of square brackets ([]) with the index in between them.
String[] anArrayOfStrings = {"string0", "string1", "string2"};
anArrayOfStrings[0]; //the first element
System.out.println(anArrayOfStrings[1]); //print the second element
anArrayOfStrings[2] = "new string value"; //assign the third element to a new value
if (anArrayOfStrings[0].equals("string0") //evaluate the first element and call a method
{
//this block will execute anArrayOfStrings[0] is "string0"
}
anArrayOfStrings[3]; //error, index out of bounds
Simply declaring the array would be
String[] names;
In your code you both declare and assign it in the same line by using an initializer list.
To assign individual elements, use the [] notation. Note that once you initialized you list to be only one String long, it cannot become longer than without be re-assigned. To declare an array of any size, you can use:
String[] arrayWithInitialSize = new String[5]; //holds five strings, each null to begin with

Categories