Java arrays value setting - java

How do I add an array value to another array while increasing the array value of the other array each time. For example, if I want array1 value to be added to array2 and when I search for the array2[position] it appears as the value of array1.
array1[position]=array2[count]
I kind of want it so that it is looped but I don't know how

From your comment -> Its going to get clumsy if you insist on arrays - using ArrayList will be much easier:
ArrayList<Item> cart = new ArrayList<>();
cart.add(array1[position]);
If you insist on using arrays you must create a new array with larger size and copy the old array into the new array each time you run out of space - actually this is what ArrayList does for your (albeit in a clever way - increasing size by 50% each time it runs out of space)

Related

Increasing Array Index without using Arraylist or Copying Elements over to another Array

I have an assignment for class that requires increasing the size of an arrays index.
The instruction mentions not to create a new array and copying the elements, calling it rather inefficient. Instead they suggest the following
"A more common strategy is to choose an initial size for the array and add elements until it is full, then double its size and continue adding elements until it is full, and so on."
I'm having trouble wrapping my head around this. How would I got about accomplishing this?
You can double the size of an array if you multiply the lenght of your current array, like this:
array = Arrays.copyOf(array, array.lenght*2);
You have to create a new array or you can do something like :
int a[] = new a[10];
a = Arrays.copyOf(a, a.length + arrayGrowNumber);
In above example you are just copying your existing array to a new array defined with large size array.
For more information please visit this link.
Initial size for the array and add elements until it is full, then
double its size and continue adding elements until it is full, and so
on.
This is statement clearly shows to use java ArrayList as this strategy is used in ArrayList.
This is how it is declared.
List<Your_DataType> lst=new ArrayList<>();
e.g.
List<Integer> lst=new ArrayList<>();
lst.add(1);
lst.add(2);
lst.add(3);
lst.get(0);// shows 1 which is at 0th location
lst.get(1);// shows 2 which is at 0th location
lst.get(2);// shows 3 which is at 0th location
Your instructions are conflicting. The "common strategy" instructions will still "create a new array and copying the elements", but will do so less often.
Say you create the array at size 20, then begin adding a total of 50 values.
After adding first 20, you create a new array of size 40 and copy values over, then continue adding to the new array.
After adding 20 more (total of 40), you create a new array of size 80 and copy values over, then continue adding to this new array.
When you've added all 50 values, you have an array of size 80, with values in the first 50 positions. You've copied the array twice.
Saying that you cannot create a new array is misleading/wrong. You have to. The "common strategy" instruction of "double its size" requires it.

How can an array size be extended to range of long in java and if not possible what other data structure can be used for the same

How can an array size be extended to range of long in java and if not possible what other data structure can be used for the same
Java arrays are built-in constructs. You cannot influence their indexing scheme in any way, so you would have to use int index.
Similarly, all Java collections are limited to 231 entries, because their size() method returns an int, and direct access methods, where available, also take an int.
If you need a data structure that stores more than 231 items, make a 2D array of "chunks", each representing a portion of a "big" array. In essence, you would build your own class that translates long addressing to a pair of ints for emulating a linear indexing space.
Java arrays' size are fixed. When you create a new array and assign it a size it can not be extended or reduced but the contents white the array can be easily changed as long as it is of the same type. Arrays in java must contain the same data type within the array.
for example :
int[] a = new int[5];
is creating a new array of size of that can store integers.
If you want to have an army that can be increased in size i would recommend using a data type called a dynamic array. In java, dynamic arrays are called ArrayList. An array list is dynamic so you do not set a size when you create the ArrayList but you must define the type of the array list
for example:
Arraylist<Integer> a = new ArrayList<Integer>();

Populate an array with unlimited index - Java

Is there a way to populate an array with unlimited indexes in java? I just want the program to keep appending to the array without any capacity.
I declared like this:
int arrInt[] = new int[]
But it says that it is missing dimension. So how can I do it?
Array in Java is static, ie. you have to declare its size while initializing. Hence the answer is 'no' and you are getting the correct message as you have not mentioned the dimension.
No, there isn't.
ArrayList serves that purpose (i.e. an array based list whose capacity increases over time automatically when adding elements to it).
Is there a way to populate an array with unlimited indexes in java?
NO
I just want the program to keep appending to the array without any
capacity.
Need to Use ArrayList
List<Object> arr = new ArrayList<Object>();
arr.add(obj1);
arr.add(obj2);
arr.add(obj3); .. so on
I declared like this - int arrInt[] = new int[]. But it says that it
is missing dimension.
Arrays will always complain to declare the size.
In java, arrays have a maximum number of elements equal to Integer.MAX_VALUE - 5. To get around this, try using a LinkedList which has an unimited number of elements. Since this is a list, you can modify the size whenever necessary in your code. Note that ArrayList also has a max number of elements of Integer.MAX_VALUE, so LinkedList is necessary if you truly need a list of unlimited size.
Resource: http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

How can I change the length of an array? [duplicate]

This question already has answers here:
Java dynamic array sizes?
(19 answers)
Closed 8 years ago.
So I am assigned with a project where I have an array and as the user puts elements into this array it will have to double in length once it gets full. We are not permitted to use array lists or anything in the collections interface. What I was trying to do was to make a new array once the old one was full, and then I would copy the values over to the new array. The problem is I don't know how many times I will have to make a new array, so I was wondering how to go about solving this.
Arrays are fixed length. If you want a data structure that has variable length use an ArrayList
Since the poster explicitly stated the requirements of the homework exclude the use of Collections an alternative approach would be to use System.arraycopy(). In such an approach you only maintain a single array and as you add items to it you use System.arraycopy() to copy the old array into a new larger array. System.arraycopy() is relatively fast and is actually how ArrayList expands its size.
If you are concerned about the cost of using System.arraycopy() you could use it only when your array is full and create a new array with more space. E.g.
Create and array of size 20. When it gets full copy it into and array of size 40. When that gets full copy it into an array of size 60...
Interestingly ArrayList increases its size by
int newCapacity = (oldCapacity * 3)/2 + 1;
when the old array is full. Presumably the writers of this put some considerable thought into how much to grow the array by when needed. It might be worth doing the same.

Adding value to list initialize list size

I have below code:
Hashtable<Integer, List<Model>> map = new Hashtable<Integer, List<Model>>();
for (int i = 0; i < arraylistAssignment.size(); i++) {
List<Model> temp = null;
for (int j = 0; j < arraylistModel.size(); j++) {
if (arraylistAssignment.get(i).getId() == arraylistModel.get(j)
.getId()) {
if (temp == null)
temp = new ArrayList<Model>();// DEBUG POINT 1
temp.add(arraylistModel.get(j));
}// DEBUG POINT 2 AFTER ADD FUNCTION ABOVE
}
map.put(arraylistAssignment.get(i).getId(), temp);
}
In the above code at debug point 1 when when i hv intitilzed the temp variable , there the object size is 0 as showm below :
but as soon as i add i.e temp.add the size is 1 but objects create is 12 out of which 11 values are null as shown below ...i could not understand the reason for null values here can anyone plz exaplin ...m i initilzing wrong?
An ArrayList is a dynamic array, what means that it grows as elements are added. But it doesn't change its size "one by one". Its size grows a "reasonable" amount, so the operation of resizing the list is not repeated each time you add an element, because this would be inefficient.
The reason for null values is because that's how ArrayLists work on the inside. They start off with a blank array inside, and as you add things they resize themselves as they see fit. The reason the array is larger than the number of objects you put in is because it'd be highly inefficient to resize the array every time you added something, so instead the ArrayList implementers just made the inner array start off at a certain size and approximately double in size every time it needs to be resized. They track how many elements you put in by tracking a separate size variable.
So in other words, you're initializing things just fine. Don't worry about the internals of the ArrayList -- if you look at the internal size variable, you'll see that it is 1, just as you expect.
ArrayList is a data structure in the Collections framework which is built on top of arrays I.e. It's implementation is done with the help of arrays. Since size is to be defined in arrays, it initializes size to be 10 at first. When you add values, it becomes the 11th item.
Now you might wonder how is this dynamic and how it works, well when size is reached to its limit it creates a new array double the size, copies the old stuff and discards the prev array. Would recommend you to take a look at the implementation.
To the user, it looks like dynamic but when you look through debugger you would see nulls. Array STARTS at 0 to 10 which makes it 11 elements and your newly added item becomes 12th but for public api, it's still the first element.
Check here for complete implementation of ArrayList: link
From Java Dokumentation:
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
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.
Default capacity is somehow 12 in your case, even though it should be 10.

Categories