length of Array of Objects in Java - java

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.

Related

What is the time complexity of the add and element in a Java Array?

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.

Can I Reuse Array Variables With Changed length?

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().

I want to add a row onto a 2d array

The method assigned in the assignment says:
boolean addLineSegment(int [] segment) - add a line segment to the database if its coordinates represent a valid line segment. This should increase the size of the lineSegment array by one and add the given line segment to the end. The method returns true if a line segment was added and false otherwise. The input should be an array of size 4.
I'm kind of stuck because I want to add a row into my array lineSegments[][] without having to reallocate it and erasing the previous contents of the array. How do I keep the contents of the array and add a new row to it so I can add the contents of segment[] to lineSegments[][]?
Use Java ArrayUtils static methods, there are many function that may help you there, like:
Add functions:
static int[] add(int[] array, int element)
Copies the given array and adds the given element at the end of the new array.
static int[] add(int[] array, int index, int element)
Inserts the specified element at the specified position in the array.
Remove functions:
static int[] remove(int[] array, int index)
Removes the element at the specified position from the specified array.
It looks like you're trying to simulate the action of an ArrayList! I'd recommend using an ArrayList to manage your list of arrays. If, however, you're only allowed to use an array, I'm afraid that unless you know how many maximum elements you're going to have in your outer array, you'll need to copy the way the ArrayList class works(with a few changes), which does indeed involve reallocating the array.
However, have no fear because you can indeed reallocate the array without losing the contents of it. In the Arrays class, there's a static method called copyOf(). This allows you to make a new array of the size you want while retaining the contents of your old array.
Let's have an example:
boolean addLineSegment(int[] segment){
if(segment is not valid)
return false;
lineSegments=Arrays.copyOf(lineSegments,lineSegments.length+1);
lineSegments[lineSegments.length-1]=segment;
return true;
}
This fulfills the requirement of increasing the size of the array by one while still retaining the old elements. For this to work, the array must start out with a size of zero, and it will then grow from then on.
This differs from the way the ArrayList class works in that while this one increases by one every time, the ArrayList class keeps track of the current index of the last element, and starts with an array of length 10, doubling every time the cap is reached. However, your requirements state that the size must increase by 1 each time so the solution I proposed should work fine.

Adding int to an array

First off don't call this a duplicate unless you actually find a thread that works for exactly what I'm trying to do, as I've gone through about 50 threads that aren't helping.
~Problem: I don't know how to correctly add an integer to an array like "private int test[] ={}"
~My code:
private int generatedList[] = {};
private int lastInt = 1;
private void startList() {
if (generatedList.length == 30000) {
System.out.println(generatedList);
} else {
generatedList[lastInt+1] = generatedList[lastInt];
lastInt++;
System.out.println(generatedList);
startList();
}
}
~What I'm trying to accomplish: if the length of the list is less than 30,000 add the last int to the array then lastInt++, so after looping say 5 times the list will print like this: 1,2,3,4,5
How do I add the "lastInt" to the generatedList[]?
Arrays in Java are of a fixed size. The one you declared is of size 0, in fact. You won't be able to append to the end of it. Check out the ArrayList class, it will help you.
private ArrayList<Integer> generatedList;
...
generatedList.add(1234);
However, there is a bigger problem with your code. Your recursive implementation is going to be extremely slow, and it doesn't have an initialization for the first value in the array. It would be much better to use a primitive array of fixed size 30,000, and simply loop from 0..30k and fill in the values by index. I leave that as an exercise for you since this is probably related to some homework assignment :)
Arrays are not extendible. This is by design.
I suggest using an ArrayList. It's like an array (can index any property, works almost as fast in terms of runtime complexity) but has the additional properties that you can add and remove items.
The easy way to do this is to change generatedList into ArrayList<Integer>. If you want to preserve an array, you can always create a new array and copy over the contents. (ArrayLists are easier, though.)
Your trying to add new elements to an array of size zero size. Use an arraylist or specify array size first.

Add a value to an array?

I've just created a new array that is one larger than my previous array and I want to copy the values in my first array into my new one. How do I add a new value to the last index of the new array?
This is what I've tried:
public void addTime(double newTime) {
if (numOfTimes == times.length)
increaseSize();
times[numOfTimes] = newTime;
}
I would recommend trying to use an object such as java.util.List rather than raw arrays. Then you can just do:
times.add(newTime) and it handles the sizing for you.
Why not you use System.arraycopy function.
increaseSIze()
{
double [] temp = new double[times.lebgth+1];
System.arrayCopy(times,0,temp,0,times.length);
times=temp;
}
after that you have times array with 1 increased size.
To set a new value to the last index you can do
times[times.length - 1] = newTime;
Array indices go from 0..n-1.
array[array.length - 1] will address the value at the end of the array.
The last item of an array is always at myArray.length - 1. In your case the last element from the times array is times[times.length - 1]. Have a look at http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html for more information about arrays.
But more importantly: If you're trying to change the capacity of your array, you are most likely using the wrong data structure for the job. Have a look at Oracle's Introduction to Collections (and especially the ArrayList class if you need an array-like index to access elements).
why wouldn't you want a java.util.ArrayList for this requirement? Practically, there won't be a need managing its size. You just simply do this:
List<Double> list = new ArrayList<Double>();
list.add(newTime);
Consider Arrays.copyOf if working with arrays is a constraint:
import java.util.Arrays;
...
private void increaseSize() {
// Allocate new array with an extra trailing element with value 0.0d
this.times = Arrays.copyOf( times, times.length + 1 );
}
...
Note that if you are doing this type array management often and in unpredictable ways, you may want to consider one of the Java Collection Framework classes such as ArrayList. One of the design goals of ArrayList is to administer size management, much like the JVM itself administers memory management.
I've developed an online executable example here.

Categories

Resources