V
V
vladocc2016-02-05 07:57:56
Java
vladocc, 2016-02-05 07:57:56

How to implement a two dimensional dynamic array in Java?

0 0 9 0 0
0 8 4 7 0
1 2 3 5 10
0 0 6 0 0
Here is a two-dimensional array of 10 numbers. When you create the first number, the next one is immediately created. One number can have several following it, as in the example with the number 3, from which three branches of the numbers 4, 5 and 6 immediately went.
The difficulty lies in the fact that the array indices belong to natural numbers, and the number 9 in this implementation will have index -1;3 , because the matrix counts from number 1.
How can you implement this type of matrix in Java?
PS zeros denote elements equal to null.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Khmyrov, 2016-02-05
@vivcogit

It seems to me that this is not an array, but a binary tree is needed.

A
Alexander Dorofeev, 2016-02-05
@TechCloud

Use Map
in conjunction with Pair :

import javafx.util.Pair;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Main {

    public static void main(String[] args) throws IOException {

        Pair<Integer, Integer> position = new Pair<Integer, Integer>(-1, 3);
        Map<Pair<Integer, Integer>, Integer> myMatrix = buildMatrix();
        myMatrix.put(position, 9);
        outputValue(myMatrix, position);


    }

    private static Map<Pair<Integer, Integer>, Integer> buildMatrix() {

        return new HashMap<>();

    }

    private static void outputValue(Map<Pair<Integer, Integer>, Integer> map, Pair<Integer, Integer> key) {


        System.out.println(map.get(key));

    }


}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question