如何在 Java 中表示静态结构

How to represent static struct in Java

本文关键字:表示 静态 结构 Java      更新时间:2023-10-16

以下是C++中的静态结构。这怎么能用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}};

谢谢

在java中,

你可以创建一个Pair对象的集合/数组,或者使用一个多维数组(数组数组);

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

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) ..... }

没有"静态结构"。 您拥有的相当于:

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}
};

C++语法允许类型定义替换变量声明中的类型名称。

可能您知道如何将这两个独立的部分转换为Java?

这可能是你在(惯用的)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))       
);

在Java中没有结构。您以类似的方式使用类。

在这种情况下,您应该有一个用于要保留的数据结构的类。

许多可能的实现之一是:

public class DataStructure {
private int c1;
private int c2;
public DataStructure(int c1, int c2) {
this.c1 = c1;
this.c2 = c2;
}
public int getC1() {
return c1;
}
public void setC1(int newC1) {
c1=newC1;
}
... //Same for C2
}

}

然后,您可以使用单个对数组作为特定类的静态变量,并且您可以让类定义这些 DataStructure 对象的静态数组,由 2 个整数组成,每个整数都像 yo udefined,或者由您想要的任何内容组成,如果您以不同的方式定义类。

Java 中没有直接翻译。

可以使用内部类代替结构,假设您计划修改每个数组元素的字段。

若要对 c/c++ 语义进行紧密建模,可以使成员变量的作用域public

如果您打算将它们设为只读,则可以将它们设为final 。或者,如果元素的数量也是固定的,您甚至可以为此数据集定义枚举。

没有一个很好的方法来减少写一堆new Pair(...)的"仪式"。当所有字段的类型相同时,您可以编写一个工厂方法,该方法采用参数的 n 元素 x n 字段数组...但是您丢失了一些编译时正确性检查。