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

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.

Related

Creating a member function /method/, which makes array of primitive data types - int, double, String simultaneously

I have a homework task where I am required to write only 1 method (a member of class MainClass) which creates simultaneously more than one type of array -with only using this method. I tried to create a method that returns the corresponing type but then it can only be done with one type of array (see the commented code /function/). My question is how can I create sort of a templated function which returns all types at once my attemp is below, /but sadly not working/?
import java.lang.reflect.Array;
import java.sql.SQLOutput;
import java.util.Arrays;
public class MainClass {
//ще направим отделни методи за класовете
/*public int [] returnArr(){
int [] ar = new int[10];
return ar;
}*/
public void createArray(){
//here I create more than one type of array:
int []ar = new int[10];
String[] str = new String[10];
double [] dbl = new double[10];
}
}
class Test{
public static void main(String[] args) {
MainClass mcl = new MainClass();
/*int [] ia = mcl.returnArr();
for (int i = 0;i<10;i++){
Arrays.fill(ia,0,9,8);
}*/
mcl.createArray();
//here the ar[] array is not accessible
Arrays.fill(ar,0,9,0);
for (int i:ar){
System.out.println(i);
}
}
}
I hope you are practicing OOPs. In Java , its not possible for a method to return multiple types. You have mentioned, you need to create multiple types of arrays using a single method. You can go by 2 methods here.
The Object oriented way - use the instance variables & initialize them in one method. It would be something like below
public class MainClass {
private int[] intArray;
private String[] strArray;
private double[] dblArray;
public void createArray() {
this.intArray = new int[10];
this.strArray = new String[10];
this.dblArray = new double[10];
}
}
And then you can use some getter methods to access the arrays.
Return array of arrays - You can return multiple values as a composite type array. For example array of java.lang.Object. Since Object is the parent class of everything in Java, an array of Object can hold any types. then your method would look like
public Object[] createArray()
{
int[] intArray = new int[10];
String[] strArray = new String[10];
double[] dblArray = new double[10];
Object[] returnArray = new Object[] { this.intArray, this.strArray, this.dblArray };
return returnArray;
}
Now in the Object array that is returned
Object[] arrays = mcl.createArray();
// arrays[0] is an integer array, arrays[1] is string array and so on.
int[] arr = arrays[0];
Now you can use the arrays in the manner you need. Hope you are clear on the concept.

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.

Initializing large number of arrays in 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);
}

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));

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