java 在java中创建元组的简单方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14575074/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:44:04  来源:igfitidea点击:

Simplist way to create a tuple in java?

javatuples

提问by omega

Is there a simple way to create a 2 element tuple in java? I'm thinking of making a class and declaring the variables as final. Would this work?

有没有一种简单的方法可以在 java 中创建一个 2 元素元组?我正在考虑创建一个类并将变量声明为最终变量。这行得通吗?

回答by duffymo

This is as simple as it gets:

这很简单:

public class Pair<S, T> {
    public final S x;
    public final T y;

    public Pair(S x, T y) { 
        this.x = x;
        this.y = y;
    }
}

回答by yshavit

Yes. Best practices would be to make the fields private and provide getters for them.

是的。最佳实践是将字段设为私有并为它们提供 getter。

For many people (including [most of?] the language designers), the idea of a tuple runs counter to the strong typing philosophy of Java. Rather than just a tuple, they would prefer a use-case-specific class, and if that class only has two getters and no other methods, so be it.

对于许多人(包括 [大多数?] 语言设计者)来说,元组的想法与 Java 的强类型哲学背道而驰。与其只是一个元组,他们更喜欢特定于用例的类,如果该类只有两个 getter 而没有其他方法,那就这样吧。

回答by anthropomo

I'd prefer the variables private with getters, no setters. Set in the constructor, obviously. Then implement iterable, maybe.

我更喜欢带有 getter 的私有变量,没有 setter。显然,在构造函数中设置。然后实现迭代,也许。