K
K
krembrule20162019-06-04 19:49:33
Java
krembrule2016, 2019-06-04 19:49:33

How to access the elements of a two-dimensional collection?

Hello!
Made a two-dimensional collection here. Here she is:

public class Collection {
    ArrayList<ArrayList<Integer>> collectionOfPoints;
    ArrayList<Integer> subCollectionOfPoints;
    int x, y;
    public Collection(){
        collectionOfPoints = new ArrayList(); 
        x = 0;
        y = 0;
    }
    public void calculatePoints(){
        for(int i = 0; i < 10; i++){
            x++;
            y++;
            subCollectionOfPoints = new ArrayList<Integer>();
            subCollectionOfPoints.add(x);
            subCollectionOfPoints.add(y);
            collectionOfPoints.add(subCollectionOfPoints);
        }
        System.out.println("Коллекция точек создана!");

    }
    public ArrayList returnCallOfPoints(){
        return collectionOfPoints;
    }
}

In short, everything is simple. A collection is made of collections, each of which contains a pair of points. Everything works, prints as it should and all that.
if(ОбъектКлассаСРеализациейДвумернойКоллекции.returnCallOfPoints().size() != 0){
        System.out.println(ОбъектКлассаСРеализациейДвумернойКоллекции.returnCallOfPoints().get(1));
    }

As a result, I have [2, 2] in the console, which is logical.
Only I need to refer to the second or first value of the nested collection. Logic dictates that you should write something like this:
System.out.println(ОбъектКлассаСРеализациейДвумернойКоллекции.returnCallOfPoints().get(1).get(1));

But, the creators of Java apparently had a different logic from mine (God bless them).
How to do it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
justAnotherCluelessUser, 2019-06-04
@krembrule2016

I will not explain that it would be more correct to call it an integer matrix, that it is not necessary to give the class the name of a standard interface, and much more ...
Well, what's the question?
In principle, you argue correctly ...
Just do not return the insides.
better make a setter/getter, where you will check for possible errors, etc.
type

Integer getValueByIndexies(int x, int y){
//всякие проверки, чтоб небыло неконтролируемых эксепшнов, типа аутОфРэндж
return collectionOfPoints.get(x).get(y);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question