How to fill a two Dimensional ArrayList in java with Integers?

前端 未结 8 2459
迷失自我
迷失自我 2020-12-15 01:57

I have to create a 2d array with unknown size. So I have decided to go with a 2d ArrayList the problem is I\'m not sure how to initialize such an array or store information.

8条回答
  •  甜味超标
    2020-12-15 02:22

    Your example looks like you want to have a map from pairs of ints to booleans (with the default value being false). If this is a sparse map (i.e. really most of the positions are false), you may be better with something like a HashSet or similar (with being a class encapsulating two ints with a suitable implementation of hashCode and equals).

    class IntPair {
       int first;
       int second;
       public boolean equals(Object o) {
          return o instanceof IntPair &&
             ((IntPair)o).first == first &&
             ((IntPair)o).second == second;
       }
       /** optimized for small numbers */
       public int hashCode() {
           return first + second * 44729;
       }
       public String toString() {
         return "(" + first + ", " + second + ")";
       }
    }
    

    Then, to say "0 connects 1" you would write

    set.add(new IntPair(0,1));
    

    It really depends on what operations you want to use afterwards - such a HashSet has quick lookup and change and uses not too much space, but you can't get quickly "all neighbours of node 1". If you need such access, you may simply want a class like

    class Node {
       int id;
       Set neighbours;
    }
    

    and additionally a list/array/set of such nodes.

    The question "array of unknown size" is not specific enough to really answer competently.

提交回复
热议问题