0

I have this in Javascript:

var population = [];
for(i=0; i < size; i++){
    population[i] = functionWhichReturnsArrays();
}

A single dimensional array containing multiple arrays in different indices - this is what I want and not a 2D array.

How can I translate this to Java?

4
  • 1
    You don't (with arrays). Javascript has dynamic arrays. Java does not. Commented Oct 5, 2017 at 11:06
  • What's another way to do this in Java? Commented Oct 5, 2017 at 11:08
  • 1
    Object[] population = new Object[size]; to create the array, then a for loop similar to the JS one to populate it. Commented Oct 5, 2017 at 11:15
  • Where is the distinction between an array of arrays and a 2D-Array? Commented Oct 5, 2017 at 12:12

3 Answers 3

1

This gives you an idea on how to approach it in Java (the code can be written a lot fancier but this is easy to follow):

public class Pop {

public static void main(String[] args) {
    new Pop().build(10);
}

private void build(int size) {
    String[][] population = new String[size][];
    for (int i = 0; i < size; i++) {
        population[i] = functionWhichReturnsArrays();
    }

    for (int a = 0; a < population.length; a++) {
        for (int b = 0; b < population[a].length; b++) {
            System.out.print(population[a][b] + " / ");
        }
        System.out.println();
    }
}

private String[] functionWhichReturnsArrays() {
    String[] strs = new String[2];
    strs[0] = "zero";
    strs[1] = "one";
    return strs;
}

}

Result will be 10 rows:

zero / one / 
zero / one / 
...
zero / one / 
Sign up to request clarification or add additional context in comments.

Comments

0
// var population = [];
ArrayList<TYPE_RETURNED_FROM_FUNTION> population = new ArrayList<>();

for (int i = 0; i < size; i++) {
    // adds at the end of the array Liste; wich is i
    population.add(functionWhichReturnsArrays());
}

1 Comment

I believe TYPE_RETURNED_FROM_FUNTION must be an array / list so you can be more specific here.
0

tl;dr

Use an ArrayList.

Answer

Java offers lots of data structures to choose from with the built in Collections. The decision which one to use is highly dependent on the nature of the specific use case. Usually it's a tradeoff between flexibillity and performance.

From the sparse description you provided I assume that your requirements to the data structure are more or less the following

  • Don't know or care about the number of elements
  • A data structure that keeps the order of the elements
  • A need to access the elements by an index

While the latter two are fullfilled by a Java array the first one is not since arrays have a fixed size. Unless there are more specific requirements I'd suggest to use an ArrayList.

As an example I create lists of random Numbers and random length in somethingThatReturnsAList(). Of cause you can use other value-types than Numbers here. Also, it should be possible to use completely different value-types for each list entry.

The list of lists, that you asked for is created in the main method at the end.

printThat() just prints contents of the number-lists for each index of the list of lists with the help of a StringBuilder.

import java.util.ArrayList;
import java.util.List;

public class ListTest {

  public static List<Number> somethingThatReturnsAList() {
    int          count;
    int          value;
    List<Number> result;

    // Random number of elements.
    count  = (int) (Math.random() * 10);
    result = new ArrayList<Number>(count);

    for (int i = 0; i < count; ++i) {
      // Random value.
      value = (int) (Math.random() * 10);
      result.add(value);
    }

    return result;
  }

  public static void printThat(List<List<Number>> listOfLists) {
    StringBuilder bldr;
    List<Number>  subList;

    bldr = new StringBuilder();

    bldr.append("The contents:\n");

    for (int i = 0; i < listOfLists.size(); ++i) {

      // Top list index.
      bldr.append(i).append(": ");
      subList = listOfLists.get(i);

      // List sub list values.
      for (int j = 0; j < subList.size(); ++j) {
        if (j > 0) {
          bldr.append(", ");
        }
        bldr.append(subList.get(j));
      }

      System.out.println(bldr.toString());

      bldr.setLength(0);
    }
  }

  public static void main(String[] args) {
    int                 size;
    List                subList;
    List<List<Integer>> listOfLists;

    size        = 5;

    // Create that list of lists
    listOfLists = new ArrayList<List<Integer>>(5);
    for (int i = 0; i < size; ++i) {
      subList = somethingThatReturnsAList();
      listOfLists.add(subList);
    }

    // Print that list of lists
    printThat(listOfLists);
  }
}

This prints something like:

The contents:
0: 5, 1, 2
1: 
2: 4, 2, 9, 3, 0, 7, 6
3: 0, 1, 5, 7, 6, 5, 1, 4, 5
4: 7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.