0

Can I create an array like this in java???

Array
([0]
    array
    [items1] = "one"
    [items2] = "two"
    [items3] = "three")
([1]
    array
    [items1] = "one###"
    [items2] = "two###"
    [items3] = "three#")

Thanx for your help

0

4 Answers 4

3

Yes, you can do this by creating an array of arrays. For example:

String[][] twoDimensionalPrimitiveArray = {
    {"one", "two", "three"},
    {"one###", "two###", "three###"}
};

You can also do this with the collection types:

List<List<String>> listOfLists = new ArrayList<>();
listOfLists.add(createList("one", "two", "three"));
listOfLists.add(createList("one###", "two###", "three###"));

// ...

private static List<String> createList(String... values) {
  List<String> result = new ArrayList<>();
  for (String value : values) {
    result.add(value);
  }
  return result;
}

Edit
@immibis has rightly pointed out in the comments that createList() can be written more simply as new ArrayList(Arrays.asList(values)).

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

1 Comment

A shorter version of createList: {return new ArrayList<>(Arrays.asList(value));}`
2

Yes, you can define an array of arrays:

    String[][] arrayOfArrays = new String[2][]; // declare and initialize array of arrays
    arrayOfArrays[0] = new String[3]; // initialize first array
    arrayOfArrays[1] = new String[3]; // initialize second array

    // fill arrays
    arrayOfArrays[0][0] = "one";
    arrayOfArrays[0][1] = "two";
    arrayOfArrays[0][2] = "three";
    arrayOfArrays[1][0] = "one###";
    arrayOfArrays[1][1] = "two###";
    arrayOfArrays[1][2] = "three#";

And to test it (print values):

    for (String[] array : arrayOfArrays) {
        for (String s : array) {
            System.out.print(s);
        }
        System.out.println();
    }

Comments

1

For two dimension arrays in Java you can create them as follows:

// Example 1:
String array[][] = {"one", "two", "three"},{"one###", "two###", "three###"}};

Alternatively you can define the array and then fill in each element but that is more tedious, however that may suit your needs more.

// Example 2:
String array[][] = new String[2][3];
array[0][0] = "one";
array[0][1] = "two";
array[0][2] = "three";
array[1][0] = "one###";
array[1][1] = "two###";
array[1][2] = "three#";

Comments

0
String[] twoDArray[] = {{"one", "two", "three"}, {"one###", "two###", "three###"}};

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.