Storing number pairs in java

后端 未结 5 731
栀梦
栀梦 2021-01-17 11:54

How do I store a set of paired numbers in java? Do I use lists or arrays or maybe something else?

eg. [ (1,1) , (2,1) , (3,5)]

5条回答
  •  囚心锁ツ
    2021-01-17 12:41

    There are a few options:

    Write a custom IntPair class

    class IntPair {
      // Ideally, name the class after whatever you're actually using 
      // the int pairs *for.*
      final int x;
      final int y;
      IntPair(int x, int y) {this.x=x;this.y=y;}
      // depending on your use case, equals? hashCode?  More methods?
    }
    

    and then create an IntPair[] or a List.

    Alternately, create a two-dimensional array new int[n][2], and treat the rows as pairs.

    Java doesn't have a built-in Pair class for a few reasons, but the most noticeable is that it's easy enough to write a class that has the same function, but has much more enlightening, helpful names for the class, its fields, and its methods.

    If we knew more about what you're actually using this for, we might be able to provide more detailed suggestions -- for all we know, a Map could be appropriate here.

提交回复
热议问题