Initializing large number of arrays in Java? - java

I am writing an program for an engineering application that needs a large number of 1x3 arrays to store coefficients for a very long rigid body mechanics equation. As such, I have about 90 arrays that need to conform to a very specific and longstanding engineering syntax. Imagine I have the following:
double[] a = {0.0, 0.0, 0.0}
double[] b = {0.0, 0.0, 0.0}
double[] c = {0.0, 0.0, 0.0}
etc.......
double[] zz = {0.0, 0.0, 0.0}
You can see that this is quite unwieldy.
As I understand from reading this discussion on primitive declaration in Java, there is no way to initialize a list of variables to the same value. For instance, in the following code:
double[] a, b, c, ...... zy, zz = new double[3];
However, this only initializes array zz, is there really no better way to initialize a large number of arrays than with the first method in this post? Is there a better overall approach to storing a large number of arrays that need to be descriptively named? I would like to be able to store the data in a two dimensional array but unfortunately these values need to be descriptive.
For reference, I need to initialize these arrays because the data that is being assigned to them originates from a list that is passed to the object instance when it is constructed. I can't assign a value to an uninitialized variable or I get a NullPointerException. For example:
a[index] = listWithDataIWantToAssign.get(listIndex);
returns a NullPointerException when using the second (invalid) method of initialization mentioned above.

If you have to work with a large ammount of arrays it's preferable to use a double array instead of excessive ammount of variables. I recommand you to create a simple double array double[][] myArray = new double[90][3]
Is there a better overall approach to storing a large number of arrays that need to be descriptively named?
if all variables are named it will be difficult to not type all names. But instead of name variables why not name values it by ints using static names ?
you can create a class keeping all names like that :
public static class VariablesNames{
private static int counter = 0;
public static final int NAME_1 = counter++;
public static final int NAME_2 = counter++;
public static final int NAME_3 = counter++;
...
}
Then use these variables in your code
double val = myArray[VariablesNames.NAME_1][0];
is there really no better way to initialize a large number of arrays than with the first method in this post?
If you have a really large ammout of arrays, it's not really usefull to initialise all arrays at the beginning. You can lazy load the array and use getter an setter on it
double[][] myArray = new double[90][];
public void init(int position){
if(myArray[position] == null){
myArray[position] = new double[3];
}
}
public double[] get(int position) {
init(position);
return myArray[position];
}
public void set(int position, List<Double> listWithDataIWantToAssign){
init(position);
for (int i = 0; i < 3; i++) {
myArray[position][i] = listWithDataIWantToAssign.get(i);
}
}
Then use these methods in your code
set(VariablesNames.NAME_2, listWithDataIWantToAssign);
double val = get(VariablesNames.NAME_2)[1];

The following code will return a 2d array of 'double' primitives, with size [N][3]. N is the number of arrays, or 90 in your example, and 3 the three double numbers in each array:
public static double[][] initDoubleArrays (int N) {
double[][] doublesArray = new double[N][3];
// the doubles will be set to 0.0 by default.
return doublesArray;
}
Alternatively, the following code will return a list where each element is a Double[] array with three Double objects
public static List<Double[]> initArrays (int nArrays) {
List<Double[]> arrays = new ArrayList<Double[]>(nArrays);
for (int i = 0; i<nArrays; i++) {
Double[] doubles = { 0.0, 0.0, 0.0 };
arrays.add(doubles);
}
return arrays;
}

Since a List couldn't be the best approach you should consider creating your own Factory, improved a little by maybe playing with the size, and the initial value...
like:
public class MyClass implements IArrayFactory {
public static void main(String[] args) {
MyClass foo = new MyClass();
List<List<Double>> l = new ArrayList<>();
for (int i = 0; i < 10; i++) {
l.add(foo.getListDouble(3, 0.0));
}
System.out.println(l);
}
#Override
public List<Double> getListDouble(int size, double initVal) {
Double[] d = new Double[size];
Arrays.fill(d, initVal);
return Arrays.asList(d);
}
}
interface IArrayFactory {
List<Double> getListDouble(int size, double initVal);
}

Related

Test2 Array Initialization Error

My class Test2 has a method to return area. It accepts a variable number of argument (Varargs) and I am trying to add alternative Varargs into the array lengthOfSide and breadthOfSide using a for loop but I am getting an ArrayOutofBoundException. Why am I getting this and how do I fix it?
class Test2 {
public double returnArea(double... corner){
double[] lengthOfSide = {};
double[] breadthOfSide = {};
int i = 0;
for(double x : corner){
lengthOfSide[i] = x;
breadthOfSide[i] = x;
System.out.println(lengthOfSide[i]);
System.out.println(breadthOfSide[i]);
i++;
}
}
}
public class Test1 {
public static void main(String args[]){
Test2 total = new Test2();
total.returnArea(34.2,22.3,332.2,223.3,22.4);
}
}
Java arrays have a fixed length. You currently create two arrays of length 0. Change
double[] lengthOfSide = {};
double[] breadthOfSide = {};
to something like
double[] lengthOfSide = new double[corner.length];
double[] breadthOfSide = new double[corner.length];
You are basically trying to modify an existing array which is not allowed...
Arrays in java are fixed sized and you can't modify them after you have created them.
basically,
double[] lengthOfSide = {};
double[] breadthOfSide = {};
this lines created an array for you (empty array).
where as in loop you are trying to assign a value to index in array that does not exist.
lengthOfSide[i] = x;
breadthOfSide[i] = x;
result is excetion.
if You want to achieve what i guess is right you should initialize it to some length you want ie. corner.length
so it should be,
double[] lengthOfSide = new double[corner.length];
double[] breadthOfSide = new double[corner.length];
also if you still want to go with the same flow try considering using arraylist for purpose.
You should specify the length of array when you create one. And after this you can't change array length. There are 2 arrays with length of 0 in your example.

creating arrays within ArrayList java

I'm trying to create two different types of Arrays within one ArrayList. Set up constructors accordingly (I think), but when it comes to instantiating them I get an error message "arr cannot be resolved". I'm slowly but surely going round the bend. How do I get the ArrayList to accept a simple array with doubles? (It also has to accept other types so it's not just a question of changing the ArrayList itself).Here's the code for the constructors & main ArrayList:
class NumList implements Num
{
private ArrayList<Num> n1;
public NumList( NumDouble[] doubleArray )
{
n1 = new ArrayList<Num>();
for( NumDouble d : doubleArray )
n1.add( d );
}
public NumList(NumFloat[] floatArray )
{
n1 = new ArrayList<Num>();
for( NumFloat d : floatArray )
n1.add( d );
}
// methods of Num interface
}
And my test class looks like this -
import java.util.ArrayList;
public class Demo extends NumList {
public Demo(NumDouble[] doubleArray) {
//suggested automatically to add super here
super(doubleArray);
double[] arr = {(1.1), (2.2), (3.3), (4.4)};
ArrayList<Num> n1 = new ArrayList<Num>(arr);
}
public static void main (String [] args){
arr.sqrt();
System.out.println("The numbers sq are "+ arr [0]);
}
}
The NumList class has just three methods including sort. I have tried wildcards as well as
It's probably something really easy ... any help appreciated.
Your ArrayList holds object of type Num, but you are trying to insert plain ol' doubles into it
double[] arr = {(1.1), (2.2), (3.3), (4.4)};
ArrayList<Num> n1 = new ArrayList<Num>(arr);
double does not inherit from Num and so cannot be placed in an ArrayList<Num>. Also, no ArrayList constructor takes an array as a parameter, you have to convert your array to a collection with Arrays.asList(array). You would have to do something like this
NumDouble[] arr = {new NumDouble(1.1), new NumDouble(2.2), new NumDouble(3.3), new NumDouble(4.4)};
ArrayList<Num> n1 = new ArrayList<Num>(Arrays.asList(arr));

Copying values of array at specific indices to another array

I came up to a situation where I have an array and I need to copy some specific attributes (i.e. values at specific indinces) not the whole array to another array.
For example if the initial array is:
double[] initArray = {1.0, 2.0, 1.5, 5.0, 4.5};
then if I wanted to copy only 2nd, 4th and 5th attribute (i.e. values at these indices) the desired output array would be:
double[] reducedArray = {2.0, 5.0, 4.5};
I know that if the indices appear in a sequential form, e.g. 1-3 then I can use System.arraycopy() but my indices does not have that aspect.
So, is there any official way to do this, besides the trivial loop through each value and copy the ones needed:
double[] includedAttributes = {1, 4, 5};
double[] reducedArray = new double[includedAttributes.length];
for(int j = 0; j < includedAttributes.length; j++) {
reducedArray[j] = initArray[includedAttributes[j]];
}
Using streams, it's a one-liner.
Given:
int[] indices;
double[] source;
Then:
double[] result = Arrays.stream(indices).mapToDouble(i -> source[i]).toArray();
Simply said, its not possible, unless you have a specific case.
for example:
You want the top N items with highest value (in your case {2.0,4.5,5.0})
A quick(and dirty) way of doing it:
public static double[] topvalues(int n,double[] original){
double[] output=new double[n];
Arrays.sort(original);
System.arraycopy(original,0,output,0,n);
return output;
}
NOTE: this method also sorts your original array as well. if you don't want this behaviour there are different methods to use, here is a list of them :
Answering your question in a way perhaps not sought-after, you could write a class for this kind of operation:
public class PointerArray <T> {
private T[] arr;
private int[] indices;
public PointerArray(T[] arr, int[] indices) {
this.arr = arr;
this.indices = indices;
}
public T get(int index) {
return this.arr[this.indices[index]];
}
public void set(int index, T value) {
this.arr[this.indices[index]] = value;
}
public int size() {
return this.indices.length;
}
}
This is untested code, but the idea in the very least should get through.
Using it would look something like this:
int[] includedAttributes = {0, 3, 4};
PointerArray<Double> reducedArray =
new PointerArray<Double>(initArray, includedAttributes);
for(int j = 0; j < reducedArray.size(); j++) {
System.out.println(reducedArray.get(j));
}
This is performance- and memory-wise, I think, a good solution, since nothing is copied (nor created). Only drawback is the need to call get(), but I have no idea how expensive method calls really are.

Method element(int) is undefined for ArrayList<double>

protected ArrayList<double[]> amostra = new ArrayList<double[]>();
public double[] element(int k){
return amostra.get(k);
public static void main(String args[]){
double k[]= {4,5,6};
double k1[]= {0,0,0};
double k2[] = {1,1,3};
ArrayList<double[]> amostra = new ArrayList<double[]>();
amostra.add(k);
amostra.add(k1);
amostra.add(k2);
amostra.size();
System.out.println(amostra.element(1));
So this is my code, I'm adding vectors to an arraylist amostra, and I wanted to print to the console the elements in position k, but when i try to do it i get the error
The method element(int) is undefined for the type ArrayList
Any help would be appreciated :)
ArrayList does not have element(int) method. That's the message the compiler is sending to you. Use get(int x) instead, it will return the double array (not vector!), stored at the x position of the ArrayList:
int x;
double[] doubleArray = amostra.get(x);
if you want to access to an specific position of one of the arrays in the array list, you should use something like:
amostra.get(arrayListPosition)[doubleArrayPosition];
this last line will return a double.

Ordering the items in the array

Hi am trying to draw polygons on the map depending on the shortest distance.
i have created the array list called distancearray.
but i want to create a new array list called shortdistance, this array list must have the same values in the distancearray but it must be shorted in assending order depending on the distance.
can any one help me to create this shortdistance array. Thank you.
String array[][]=dbhand.collecting(getIntent().getExtras().getString("temple_type"), Integer.parseInt(getIntent().getExtras().getString("notemples")));
for(int i=0;i<array.length;i++){
displaymarkers(Double.parseDouble(array[i][0]), Double.parseDouble(array[i][1]), array[i][2]);
}
for(int i=0;i<array.length;i++){
double Distance = calculate_distance(SEATTLE_LAT, SEATTLE_LNG, Double.parseDouble(array[i][0]), Double.parseDouble(array[i][1]));
double[][] distancearray = new double[array.length][3];
distancearray[i][0]=Double.parseDouble(array[i][0]);
distancearray[i][1]=Double.parseDouble(array[i][1]);
distancearray[i][2]=Distance;
}
double [][] shortdistance = new double [array.length][3];
Draw Polygon Function
private void drawpolygon(String array[][]) {
int lengh = array.length;
if(lengh==2){
mMap.addPolygon(new PolygonOptions()
//.add(new LatLng(9.662502, 80.010239), new LatLng(9.670931, 80.013201), new LatLng(9.663216, 80.01333))
.add(new LatLng(9.6632139, 80.0133258))
.add(new LatLng(Double.parseDouble(array[0][0]), Double.parseDouble(array[0][1])))
.add(new LatLng(Double.parseDouble(array[1][0]), Double.parseDouble(array[1][1])))
.fillColor(Color.GRAY));
}
Just call Arrays.sort() against your array and specify a comparator that looks at the distance.
You are going to have difficulty sorting your arrays as-is because you currently store your data in parallel arrays:
distancearray[i][0]=Double.parseDouble(array[i][0]);
distancearray[i][1]=Double.parseDouble(array[i][2]);
distancearray[i][3]=Distance;
You can sort distancearray[n] but that will give you nonsense results. Instead what you should do is create a small class that implements Comparable (comparing based on distance) that holds your three values, then work with an array of those classes:
class DistanceInfo implements Comparable<DistanceInfo> {
public double a;
public double b;
public double distance;
public DistanceInfo (double a, double b, double distance) {
this.a = a;
this.b = b;
this.distance = distance;
}
#Override public int compareTo (DistanceInfo d) {
return Double.compare(distance, d.distance);
}
}
// then:
DistanceInfo[] distancearray = new DistanceInfo[array.length];
// and you can load it using the constructor:
for (int i = 0; i < array.length) {
double a = Double.parseDouble(array[i][0]);
double b = Double.parseDouble(array[i][1]);
distancearray[i] = new DistanceInfo(a, b, Distance);
}
(The fields can be made final if you wish to specify that they cannot be modified after construction.)
Now, Arrays.sort() will sort distancearray based on distance:
Arrays.sort(distancearray, null);
You could also use an ArrayList<DistanceInfo> instead, the idea is the same except you sort with Collections.sort().
In general, for this reason (among others) it is usually better to use a class to store all information about an object as opposed to parallel arrays.
As an aside, you may want to consider using this class for array as well, it will simplify your code a bit (you can modify displaymarkers to take a DistanceInfo, and you can also avoid parsing the same double more than once).

Categories