Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Java have an equivalent variable type to C#'s Tuple?

Tags:

java

c#

.net

tuples

I am translating a program from C# to Java. In the C# code, the developer uses Tuple. I need to translate this C# code into Java code. Therefore, does Java have an equivalent variable type to C#'s Tuple?

like image 216
Atish Dipongkor Avatar asked Apr 24 '13 16:04

Atish Dipongkor


People also ask

Does Java have a VAR equivalent?

You can take a look to Kotlin by JetBrains, but it's val. not var. Kotlin has val and var. val is equivelent to declaring a variable final in java, var allows reassignment.

Do Java and C have the same syntax?

Java is a statically typed object-oriented language that uses a syntax similar to (but incompatible with) C++. It includes a documentation system called Javadoc. Extends C with object-oriented programming and generic programming. C code can most properly be used.

Are there Typedefs in Java?

In one line, There is nothing in Java which is equivalent to typedef of C++. In Java, class is used to name and construct types or we can say that class is the combined function of C++'s struct and typedef.

What is difference between C and Java?

C is a compiled language that is it converts the code into machine language so that it could be understood by the machine or system. Java is an Interpreted language that is in Java, the code is first transformed into bytecode and that bytecode is then executed by the JVM (Java Virtual Machine).


2 Answers

Due to type erasure, there is no way in Java to have exact mirrors of the various Tuple classes in .NET. However, here is a BSD-licensed implementation of Tuple2 and Tuple3 for Java, which mirror the Tuple<T1, T2> and Tuple<T1, T2, T3> types from .NET.

  • Tuple.java (static methods to construct tuples with type inference)
  • Tuple2.java
  • Tuple3.java

One cool thing you can do in Java but not C# is this:

class Bar extends Foo { }

...

Tuple2<? extends Foo, ? extends Foo> tuple = Tuple.create(new Bar(), new Bar());

In C#, you would have to use casts instead:

Tuple<Foo, Foo> tuple = Tuple.Create((Foo)new Bar(), (Foo)new Bar());
like image 130
Sam Harwell Avatar answered Sep 28 '22 21:09

Sam Harwell


I was in need of Tuple equivalent in my android project as well, but didn't found any native solution in Java. But surprisingly there is Pair.class in android's util which is exact what I was searching for.

So Android developers, who came across this question, use Pair.class in android.util package.

P.S. I'm sad to accept that there are a lot of things that Java is far behind from other languages already.

like image 40
Hayk Nahapetyan Avatar answered Sep 28 '22 20:09

Hayk Nahapetyan