Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent static struct in Java

Tags:

java

c++

Following is a static struct in C++. How can this be represented in java.

static struct {
       int c1;
       int c2;
   } pair[37]= {{3770,3780}, {3770,3781}, {3770,3782}, {3770,3785},
                {3770,3786}, {3770,3787}, {3771,3780}, {3771,3781},
                {3771,3782}, {3771,3785}, {3771,3786}, {3771,3787},
                {3772,3780}, {3772,3783}, {3773,3780}, {3773,3781},
                {3773,3782}, {3773,3785}, {3773,3786}, {3773,3787},
                {3774,3780}, {3774,3781}, {3774,3782}, {3774,3783},
                {3774,3785}, {3774,3786}, {3774,3787}, {3776,3780},
                {3776,3785}, {3776,3786}, {3776,3787}, {53,3770},
                {53,3771},{53,3772},{53,3773},{53,3774},{53,3776}};

Thanks

like image 347
JavaBits Avatar asked May 20 '11 13:05

JavaBits


3 Answers

In java you could make a collection/array of Pair objects or use an multidimensional array (array of arrays);

static int[][] pairs = new int[][] { {3770,3780}, {3770,3781}, {3770,3782}, {3770,3785} }

or

class Pair { 
  int a; 
  int b; 
  Pair(int a, int b) { this.a=a; this.b=b; } 
}

static Pair[] pairs = new Pair[] { new Pair(1,2), new Pair(2,3) ..... }
like image 66
sksamuel Avatar answered Oct 05 '22 22:10

sksamuel


There is no "static struct". What you have is equivalent to:

struct PairType {
    int c1;
    int c2;
};

static PairType pair[37]= {
            {3770,3780}, {3770,3781}, {3770,3782}, {3770,3785},
            {3770,3786}, {3770,3787}, {3771,3780}, {3771,3781},
            {3771,3782}, {3771,3785}, {3771,3786}, {3771,3787},
            {3772,3780}, {3772,3783}, {3773,3780}, {3773,3781},
            {3773,3782}, {3773,3785}, {3773,3786}, {3773,3787},
            {3774,3780}, {3774,3781}, {3774,3782}, {3774,3783},
            {3774,3785}, {3774,3786}, {3774,3787}, {3776,3780},
            {3776,3785}, {3776,3786}, {3776,3787}, {53,3770},
            {53,3771},{53,3772},{53,3773},{53,3774},{53,3776}
};

and the C++ grammar allows the type definition to replace the type name in a variable declaration.

Probably you know how to convert these two independent parts to Java?

like image 43
Ben Voigt Avatar answered Oct 06 '22 00:10

Ben Voigt


This is probably the best you can do in (idiomatic) Java:

final class Pair<A, B> {
  public final A first;
  public final B second;

  private Pair(A first, B second) {
    this.first = first;
    this.second = second;
  }      

  public static <A, B> Pair<A, B> of(A first, B second) {
    return new Pair<A, B>(first, second);
  }
}

List<List<Pair<Integer, Integer>>> pairs = Arrays.asList(
  Arrays.asList(Pair.of(3234, 3235), Pair.of(5678, 5679)),
  Arrays.asList(Pair.of(3456, 3457), Pair.of(2367, 2368))       
);
like image 43
missingfaktor Avatar answered Oct 06 '22 00:10

missingfaktor