Can I Use Array Variables With Changed Length Each Time
like
int [] primes = new int[6];
...
primes = new int[4];
Can I Use Prime Again Like I Did Above ? Is It Possible ? If Not Can You Give Me Reason Thanks .
You are not reusing the same array, but creating new instances of array object. The java array object has a fixed length (final int), so it's impossible to change the length of an array after instantiation.
Some explanation to your question.
You can run the following code and will get better understanding.
As java can't get the address, so here using hashcode to show the object address.
int[] prime = new int[]{1,2,3,4};
System.out.println(Arrays.hashCode(prime));
System.out.println("prime[0]="+prime[0]);
prime = new int[]{4,3,2,1,0};
System.out.println(Arrays.hashCode(prime));
System.out.println("prime[0]="+prime[0]);
Output like this:
955331
prime[0]=1
1045631
prime[0]=4
Array can not be resized once memory is being allocated as array get a contiguous memory block.
int arr[] = new int[3];
Once memory space is hold, resizing the array is not possible as next contiguous memory block may not be available. You can either create a new array and shift all the elements of previous array to the new array with different size.
I would recommend using ArrayList for dynamic array. If you get in any such situation.
Two separate arrays
You are not changing the length of the array. You are creating a second array, separate and distinct from the first.
You created two arrays but used only a single reference variable (primes) to track them. When you assigned the second array to primes, the first was forgotten. The first array is still floating around in memory, a candidate for eventual garbage collection if no other reference points to it.
ArrayList
If you want resizing, use a List implementation such as ArrayList rather than a mere array. You’ll need to store objects (Integer) rather than primitives (int). The auto-boxing feature in Java can mask the difference.
int initialCapacity = 6 ;
ArrayList< Integer > primes = new ArrayList<>( initialCapacity ) ;
primes.add( 7 ) ; // The primitive `int` 7 literal is automatically converted via autoboxing to be an `Integer` Object.
The ArrayList automatically grows its capacity as needed to store additional items.
If you wish to free up extra capacity not allocated to hold any objects, call ArrayList::trimToSize().
Related
I want to calculate how many records hold an Array of Objects . here's my code:
public class PoS {
int id;
String name;
double pos_gps_lat;
double pos_gps_long;
public PoS(int id, String name,double pos_gps_lat, double pos_gps_long) {
this.id=id;
this.name=name;
this.pos_gps_lat=pos_gps_lat;
this.pos_gps_long=pos_gps_long;
}
}
I added only one (1) record as fellow
PoS pos[]=new PoS[1]; // updated as requested in comments
pos[0]=new PoS(1,"test",12.123456, 12.123456);
But i get 4 as a result :
System.out.printf(pos.length);
Question 1:
How i can get the number of records and not the number of elements that an Array of Objects contains?
Question 2:
I'm going to use over 10 K records, is Array of Objects the best option in term of performance?
An array has a fixed length, and .length gives you that length (which is 4 in your case, based on the output you got). The array instance has no method that returns the number of array indices that actually reference a non-null value.
You'll have to maintain a separate int counter in order to obtain this information. This counter will also let you know in which index of the array you can assign new data.
If you want to know the actual number of elements, you can use an ArrayList instead of an array. The size() method will tell you how many elements were added to the List.
As to whether or not an array of 10000 objects is the best option, that would depend on whether you are going to fill all/most of that array, and whether or not you'll never need to store more than 10000 objects. Using an ArrayList will give you more flexibility.
Array sizes are immutable once created, so unless you want to use a mutable Collection such as a List, the length property will give you the size with which the array has been initialized.
Therefore, chances are your array has been initialized as new Pos[4], and you've only populated element at index 0 (but the length is still 4).
However since Java 8 you can also use a slightly longer construct to return the size of the non-null elements in your array:
Arrays.stream(pos).filter(Objects::nonNull).count()
The latter does the following:
Provides a stream of the array's elements
Filters by static method reference Objects::nonNull i.e. only non-null objects
Provides a long terminal operation, counting the filtered elements (e.g. in your case, probably just the one)
Note that, while syntactically concise, this operation has a higher cost than referencing a length property, as it does iterate over the array elements under the hood.
Answer to Question1, do you try this?
Object[] arrayOfObjects = new Object[2];
int length = Array.getLength(arrayOfObjects );
Note that its a general mode, you addapt it to your code.
Hello I am research about that, but I cannot found anything in the oracle website.
The question is the next.
If you are using an static Array like this
int[] foo = new int[10];
And you want add some value to the 4 position of this ways
foor[4] = 4;
That don't shift the elements of the array so the time complexity will be O(1) because if you array start at 0x000001, and have 10 spaces, and you want put some in the x position you can access by (x*sizeOf(int))+initialMemoryPosition (this is a pseudocode)
Is this right, is this the way of that this type of array works in java, and if its time complexity O(1)
Thanks
The question is based on a misconception: in Java, you can't add elements to an array.
An array gets allocated once, initially, with a predefined number of entries. It is not possible to change that number later on.
In other words:
int a[] = new int[5];
a[4] = 5;
doesn't add anything. It just sets a value in memory.
So, if at all, we could say that we have somehow "O(1)" for accessing an address in memory, as nothing related to arrays depends on the number of entries.
Note: if you ask about ArrayList, things are different, as here adding to the end of the array can cause the creation of a new, larger (underlying) array, and moving of data.
An array is somewhere in memory. You don’t have control where, and you should not care where it is. The array is initialized when using the new type[size] syntax is used.
Accessing the array is done using the [] index operator. It will never modify size or order. Just the indexed location if you assign to it.
See also https://www.w3schools.com/java/java_arrays.asp
The time complexity is already correctly commented on. But that is the concern after getting the syntax right.
An old post regarding time complexity of collections can be found here.
Yes, it takes O(1) time. When you initialize an array, lets say, int[] foo = new int[10],
then it will create a new array with 0s. Since int has 4 bytes, which is 32 bits, every time assign a value to one element, i.e., foo[4] = 5, it will do foo[32 x input(which is 4)] = value(5); That's why array is 0-indexed, and how they assign values in O(1) time.
I'm learning Java and surprisingly I found out that Java arrays are not dynamic - even though its cousing languages have dynamic arrays.
So I came out with ideas to kind of imitate a dynamic array in java on my own.
One thought I had was to copy the original array references to a temporary array, then turn the original array to null, re-set its index to a bigger value and then finally re-copy the values from the temporary array.
Example.:
if(numberOfEntries == array.length){
Type[] temp = new Type[numberOfEntries];
for(int x=0; x < numberOfEntries; x++){
temp[x] = array[x];
}
array = null;
array = new Type[numberOfEntries+1];
for(int x=0; x < numberOfEntries; x++){
array[x] = temp[x];
}
I know that this can result in data loss if the process is interrupted, but aside from that, is this a bad idea? What are my options?
Thanks!
Your idea is in the right ballpark. But for a task that you propose you should never implement your own version, unless it is for academic purposes and fun.
What you propose is roughly implemented by the ArrayList class.
This has an internal array and a size 'counter'. The internal array is filled when items are added. When the internal array is full all elements are copied to a bigger array. The internal array is never released to the user of the class (to make sure it's state is always valid).
In your example code, because an array is a pointer, you don't really need the temp array. Just create a new one, copy all elements and save the pointer to it as your array.
You might want to look into thrashing. Changing the size of the array by 1 is likely to be very inefficient. Depending on your use case, you might want to increase the array size by double, and similarly halve the array when it's only a quarter full.
ArrayList is convenient, but once it's full, it takes linear time to add an element. You can achieve something similar to resizing with the ensureCapacity() method. I'd recommend becoming more familiar with Java's Collections framework so you can make the best decisions in future by yourself.
Arrays are not dynamic their size can't change dynamically and right now you aren't changing the same object, you are replacing smaller size object with larger size object
int[5] Arr = new int[5] ; // Create an array of size 5
Arr = new int[10] ;// you assigned the different objects. It is not the same object.
So, we can't change the size of the array dynamically. You can use ArrayList for the same.
But keep try !!!
Please take a look at java.util.ArrayList which is dynamically, it is part of the Collections framework. Making the Array dynamically should be slower and error-prone.
Have you heard about time complexity , do you know how much time complexity you are increasing, Every time you are copying old array element to new array let you have 1 million element in array then think about copying time of element of one array to another array.
One more thing i want to tell you, ArrayList implementation used same logic except new length that you are using .
I first ran into my problem trying to create a int[][] of very large size (7k by 30k) for a dictionary gap list postings program. But alas I run out of space trying to allocate the array. How might I create a 2-d array of integers?
What I want is a list of list in which each list in the list is a list of integers. Here is a sample of my code.
Code:
static final int numberOfTerms = 6782;
static final int numberOfLines = 30383;
byte[][] countMatrix = new byte[numberOfLines][numberOfTerms];
int[][] gapsMatrix = new int[numberOfLines][numberOfTerms]; // To big!!
This list of lists is going to be filled with integers that represent the gaps between two occurrences of the same word in a specific text. So in count matrix I hold a byte indicating whether a word is specified for a specified index. Then in the function I am creating right now I am going through the countMatrix and if I find a byte there, I take the current index minus the last found index and save that number in my 2D-array of integers which gives me the just the gaps between each of the same word in the text.
So how might I create a data structure I need to accomplish this?
I don't know whether this will work for you but you can try Sparse Matrix as option if you want to stick to Array. There are several other options.Map, List ,Weak reference Collections etc
To create an array you need to have enough memory to create it.
An int uses 4-bytes per values and an array uses at least N * M times that.
e.g. 4 * 30383 * 6782 is about 820 MB you need to have free to create this.
This is about $8 worth of memory so this should be a big problem unless you don't have this much or you set your maximum memory too low.
I would increase your maximum memory by 1 GB at least and it should work.
Alternatives include
use a smaller size e.g. char or short or byte which is 2-4 x smaller.
use off heap memory such as a memory mapped file. This doesn't use much heap but does use disk space which is usually cheaper.
increase your maximum memory size.
You simply have insufficient memory to do that.
http://www.javamex.com/tutorials/memory/array_memory_usage.shtml
Sorry I didn't make it clear but, it is unlikely that using another DS is going to change this.
So how might I create a data structure I need to accomplish this?
If is understand correctly, then you want to record gaps between same terms.
Let us say, you have array of terms you need to analyze, then:
String[] terms = ...;
Map<String, List<Integer>> map = new TreeMap<String, <Integer>>();
for (int i = 0; i < terms.length; i++) {
String term = terms[i];
List<Integer> positions = map.get(term);
if (gaps == null) {
positions = new ArrayList<Integer>();
}
positions.add(i);
map.set(term, positions);
}
Later you just look at the positions of each term and may calculate gaps between those. (You may integrate that gaps calculation into this code, but I leave it as exercise for you).
I know array lookup has O(1) time, so it cannot be looping through. Does the program store the memory locations of the indices of the array, or how does it look the index instantaneously?
Array elements are always spaced at equal distances in the memory, so finding an element given an index requires a multiplication by the size of the element and an addition of the array's base in memory. Both operations are often done within the space of a single instruction in hardware by employing an appropriate addressing mode.
underneath...
its a memory address + (index postion * the size of the things in the array)
Try this,
1. Arrays are consecutive memory locations which are stored in Heap, as Arrays are objects in java.
2. Assume i have an Array of String as an instance variable
String[] arr = {1,2,3,4,5};
Now its like this
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
{1,2,3,4,5} are stored over the heap, and Considering array "arr" as instance variable, will lives within the object on the heap.
Now arr will hold the address of the very first element of the Array that is 1. "arr" which is an object reference array variable, will be inside the object, and {1,2,3,4,5} outside somewhere on the heap.
Array elements are stored in a consecutive block, if they grow they need to be moved to a new place. The elements are then accessed using an offset from where the array begins.
In C you can access the element of index i in an array called a using two different methods:
int arrayElement = a[i];
int arrayElement = (int)(a + i * sizeof(int));
This is more or less how it is done in Java under the hood.