Java ArrayList of Arrays?

后端 未结 7 874
情书的邮戳
情书的邮戳 2020-12-05 01:43

I want to create a mutli dimensional array without a fixed size.

I need to be able to add items of String[2] to it.

I have tried looking at:

7条回答
  •  醉酒成梦
    2020-12-05 02:30

    Since the size of your string array is fixed at compile time, you'd be better off using a structure (like Pair) that mandates exactly two fields, and thus avoid the runtime errors possible with the array approach.

    Code:

    Since Java doesn't supply a Pair class, you'll need to define your own.

    class Pair {
      public final A first;
      public final B second;
    
      public Pair(final A first, final B second) {
        this.first = first;
        this.second = second;
      }
    
      //
      // Override 'equals', 'hashcode' and 'toString'
      //
    }
    

    and then use it as:

    List> action = new ArrayList>();
    

    [ Here I used List because it's considered a good practice to program to interfaces. ]

提交回复
热议问题