I have an enum like:
enum TEST {
TEST1, TEST 2;
public abstract <T> String stringify (T input);
}
I need to add a constant specific method , something like stringify.
This method will take different types of inputs (for each enum). Can I do that? Eclipse is not letting me do it ..something like:
enum TEST {
TEST1(
public <Float> String stringify (Float input){
return String.valueOf(input);
}
)
}
You can't do it with enums, but you can simulate this behaviour with generic class:
public abstract class TEST<T> {
public static final TEST<Float> TEST1 = new TEST<Float>() {
public String stringify (Float input){
return String.valueOf(input);
}
};
public abstract <T> String stringify(T input);
}
you can do it. but it's not clear what the benefit is:
enum TEST {
TEST1 {
public <Float>String stringify(Float input) {
System.out.println("TEST1");
return String.valueOf(input);
}
},
TEST2 {
public <Integer>String stringify(Integer input) {
System.out.println("TEST2");
return String.valueOf(input);
}
},
TEST3 {};
public <T>String stringify(T input) {
System.out.println("super");
return "";
}
public <Integer>String stringify2(Object input) {
System.out.println("non generic");
return String.valueOf(input);
}
}
public class Main{
public static void main(String[] args) {
for(TEST test:TEST.values()) {
System.out.println(test.stringify(new Float(1.23)));
System.out.println(test.stringify(new Integer(42)));
System.out.println(test.stringify(new Double(4.56)));
}
for(TEST test:TEST.values()) {
System.out.println(test.stringify2(new Float(1.23)));
System.out.println(test.stringify2(new Integer(42)));
System.out.println(test.stringify2(new Double(4.56)));
}
}
}
Think of each Enum value as a class. So yes, the enums can have methods, just like a class does -- they all have the same methods though.
http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
Look at the Planet example.
Also note that the enum itself can have static methods....(just like a class)
No, you can't make each enum constant implement an abstract method but require a different type of input than the other enum constants. If you could, what would happen if you were given an instance of your TEST enum (you don't know what constant it is) and tried to call stringify on it? What type would you pass it?
Edit: Given what you've said about these enums being used to decode strings into objects, it seems to me you have several options:
You could get a String representation of each decoded object by just calling toString() on it.
You could add a set of overloaded static method on the enum class itself, called stringify(Float) and stringify(Double), etc. Then you could just call TEST.stringify(value) and if there were a stringify method for the value's type, it'd work fine.
I imagine there are other options as well.
You can't use generics with enums, because the enum constants themselves are already the concrete (singleton) instances. At instance level, the generics must already be concrete.
So, I would stringly recommend going with one of the alternatives given in the other answers.
If you must do it in an enum, you could consider the following, which at least gives you a runtime means of type checking, including ClassCastExceptions. You won't have any support from the compiler though.
public enum TestEnum {
Test1(Float.class),
Test2(Integer.class),
Test3(String.class);
private final Class<?> iInputType;
private TestEnum(final Class<?> pInputType) {
iInputType = pInputType;
}
public Class<?> getInputType() {
return iInputType;
}
public String stringify(final Object pInput) {
return String.valueOf(iInputType.cast(pInput));
}
}
Test Code:
System.out.println(TestEnum.Test1.stringify(1.23f));
System.out.println(TestEnum.Test2.stringify(42));
System.out.println(TestEnum.Test3.stringify("foo"));
// but:
// System.out.println(TestEnum.Test1.stringify("foo")); // -> ClassCastException!
for (TestEnum test : TestEnum.values()) {
for (Object input : new Object[]{1.23f, 42, "foo"}) {
if (test.getInputType().isAssignableFrom(input.getClass())) {
System.out.println(test.stringify(input));
}
}
}
Related
I have a collection (or list or array list) in which I want to put both String values and double values. I decided to make it a collection of objects and using overloading ond polymorphism, but I did something wrong.
I run a little test:
public class OOP {
void prova(Object o){
System.out.println("object");
}
void prova(Integer i){
System.out.println("integer");
}
void prova(String s){
System.out.println("string");
}
void test(){
Object o = new String(" ");
this.prova(o); // Prints 'object'!!! Why?!?!?
}
public static void main(String[] args) {
OOP oop = new OOP();
oop.test(); // Prints 'object'!!! Why?!?!?
}
}
In the test seems like the argument type is decided at compile time and not at runtime. Why is that?
This question is related to:
Polymorphism vs Overriding vs Overloading
Try to describe polymorphism as easy as you can
EDIT:
Ok the method to be called is decided at compile time. Is there a workaround to avoid using the instanceof operator?
This post seconds voo's answer, and gives details about/alternatives to late binding.
General JVMs only use single dispatch: the runtime type is only considered for the receiver object; for the method's parameters, the static type is considered. An efficient implementation with optimizations is quite easy using method tables (which are similar to C++'s virtual tables). You can find details e.g. in the HotSpot Wiki.
If you want multiple dispatch for your parameters, take a look at
groovy. But to my latest knowledge, that has an outdated, slow multiple dispatch implementation (see e.g. this performance comparison), e.g. without caching.
clojure, but that is quite different to Java.
MultiJava, which offers multiple dispatch for Java. Additionally, you can use
this.resend(...) instead of super(...) to invoke the most-specific overridden method of the enclosing method;
value dispatching (code example below).
If you want to stick with Java, you can
redesign your application by moving overloaded methods over a finer grained class hierarchy. An example is given in Josh Bloch's Effective Java, Item 41 (Use overloading judiciously);
use some design patterns, such as Strategy, Visitor, Observer. These can often solve the same problems as multiple dispatch (i.e. in those situations you have trivial solutions for those patterns using multiple dispatch).
Value dispatching:
class C {
static final int INITIALIZED = 0;
static final int RUNNING = 1;
static final int STOPPED = 2;
void m(int i) {
// the default method
}
void m(int##INITIALIZED i) {
// handle the case when we're in the initialized `state'
}
void m(int##RUNNING i) {
// handle the case when we're in the running `state'
}
void m(int##STOPPED i) {
// handle the case when we're in the stopped `state'
}
}
What you want is double or more general multiple dispatch, something that is actually implemented in other languages (common lisp comes to mind)
Presumably the main reason java doesn't have it, is because it comes at a performance penalty because overload resolution has to be done at runtime and not compile time. The usual way around this is the visitor pattern - pretty ugly, but that's how it is.
Old question but no answer provides a concrete solution in Java to solve the issue in a clean way.
In fact, not easy but very interesting question. Here is my contribution.
Ok the method to be called is decided at compile time. Is there a
workaround to avoid using the instanceof operator?
As said in the excellent #DaveFar answer, Java supports only the single-dispatch method.
In this dispatching mode, the compiler bounds the method to invoke as soon as the compilation by relying on the declared types of the parameters and not their runtime types.
I have a collection (or list or array list) in which I want to put
both String values and double values.
To solve the answer in a clean way and use a double dispatch, we have to bring abstraction for the manipulated data.
Why ?
Here a naive visitor approach to illustrate the issue :
public class DisplayVisitor {
void visit(Object o) {
System.out.println("object"));
}
void visit(Integer i) {
System.out.println("integer");
}
void visit(String s) {
System.out.println("string"));
}
}
Now, question : how visited classes may invoke the visit() method ?
The second dispatch of the double dispatch implementation relies on the "this" context of the class that accepts to be visited.
So we need to have a accept() method in Integer, String and Object classes to perform this second dispatch :
public void accept(DisplayVisitor visitor){
visitor.visit(this);
}
But impossible ! Visited classes are built-in classes : String, Integer, Object.
So we have no way to add this method.
And anyway, we don't want to add that.
So to implement the double dispatch, we have to be able to modify the classes that we want to pass as parameter in the second dispatch.
So instead of manipulating Object and List<Object> as declared type, we will manipulate Foo and List<Foo> where the Foo class is a wrapper holding the user value.
Here is the Foo interface :
public interface Foo {
void accept(DisplayVisitor v);
Object getValue();
}
getValue() returns the user value.
It specifies Object as return type but Java supports covariance returns (since the 1.5 version), so we could define a more specific type for each subclass to avoid downcasts.
ObjectFoo
public class ObjectFoo implements Foo {
private Object value;
public ObjectFoo(Object value) {
this.value = value;
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
#Override
public Object getValue() {
return value;
}
}
StringFoo
public class StringFoo implements Foo {
private String value;
public StringFoo(String string) {
this.value = string;
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
#Override
public String getValue() {
return value;
}
}
IntegerFoo
public class IntegerFoo implements Foo {
private Integer value;
public IntegerFoo(Integer integer) {
this.value = integer;
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
#Override
public Integer getValue() {
return value;
}
}
Here is the DisplayVisitor class visiting Foo subclasses :
public class DisplayVisitor {
void visit(ObjectFoo f) {
System.out.println("object=" + f.getValue());
}
void visit(IntegerFoo f) {
System.out.println("integer=" + f.getValue());
}
void visit(StringFoo f) {
System.out.println("string=" + f.getValue());
}
}
And here is a sample code to test the implementation :
public class OOP {
void test() {
List<Foo> foos = Arrays.asList(new StringFoo("a String"),
new StringFoo("another String"),
new IntegerFoo(1),
new ObjectFoo(new AtomicInteger(100)));
DisplayVisitor visitor = new DisplayVisitor();
for (Foo foo : foos) {
foo.accept(visitor);
}
}
public static void main(String[] args) {
OOP oop = new OOP();
oop.test();
}
}
Output :
string=a String
string=another String
integer=1
object=100
Improving the implementation
The actual implementation requires the introduction of a specific wrapper class for each buit-in type we want to wrap.
As discussed, we don't have the choice to operate a double dispatch.
But note that the repeated code in Foo subclasses could be avoided :
private Integer value; // or String or Object
#Override
public Object getValue() {
return value;
}
We could indeed introduce a abstract generic class that holds the user value and provides an accessor to :
public abstract class Foo<T> {
private T value;
public Foo(T value) {
this.value = value;
}
public abstract void accept(DisplayVisitor v);
public T getValue() {
return value;
}
}
Now Foo sublasses are lighter to declare :
public class IntegerFoo extends Foo<Integer> {
public IntegerFoo(Integer integer) {
super(integer);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
public class StringFoo extends Foo<String> {
public StringFoo(String string) {
super(string);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
public class ObjectFoo extends Foo<Object> {
public ObjectFoo(Object value) {
super(value);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
And the test() method should be modified to declare a wildcard type (?) for the Foo type in the List<Foo> declaration.
void test() {
List<Foo<?>> foos = Arrays.asList(new StringFoo("a String object"),
new StringFoo("anoter String object"),
new IntegerFoo(1),
new ObjectFoo(new AtomicInteger(100)));
DisplayVisitor visitor = new DisplayVisitor();
for (Foo<?> foo : foos) {
foo.accept(visitor);
}
}
In fact, if really needed, we could simplify further Foo subclasses by introducing java code generation.
Declaring this subclass :
public class StringFoo extends Foo<String> {
public StringFoo(String string) {
super(string);
}
#Override
public void accept(DisplayVisitor v) {
v.visit(this);
}
}
could as simple as declaring a class and adding an annotation on:
#Foo(String.class)
public class StringFoo { }
Where Foo is a custom annotation processed at compile time.
When calling a method that is overloaded, Java picks the most restrictive type based on the type of the variable passed to the function. It does not use the type of the actual instance.
this isn't polymoprhism, you've simply overloaded a method and called it with parameter of object type
Everything in Java is an Object/object (except primitive types). You store strings and integers as objects, and then as you call the prove method they are still referred to as objects. You should have a look at the instanceof keyword. Check this link
void prove(Object o){
if (o instanceof String)
System.out.println("String");
....
}
I have an abstract java class "BaseOperation". This class only has a single abstract method:
public abstract T execute()
{
...
return T;
}
Subclasses of BaseOperation must implement this method:
public class GetUsersOperation extends BaseOperation<GetUsersResponse>
{
...
#Override
public GetUsersResponse execute()
{
...
return GetUsersResponse;
}
}
This is a great way to put all common "operation" logic in the BaseOperation class, but still have every concrete subclass's execute() method have a different return type.
Now I need to change this structure to allow the execute() methods to have a variable amount of arguments. For example, one concrete subclass would require:
execute(String, int)
and another would need:
execute(Date, Date, String)
This is tricky, because the execute method is declared in the base class. Simply overloading the execute methods in the base is not ideal. Firstly, the amount of overloads would be huge. Secondly, every subclass will only ever use one of the execute methods, what's the point of all the others?
The (in my opinion) easiest solution would be to declare the execute method with varargs:
execute(Object... arguments)
And then downcast all arguments in the subclasses:
execute(Object... arguments)
{
String s = (String) arguments[0];
...
}
Obviously this has 2 major downsides:
Reduced performance because of all the downcasting operations
Calling the execute() methods is no longer strictly typed because any amount of objects can be passed witout compiler warnings.
Are there patterns or other solutions that could don't have these disadvantages?
You could use a bean holding the parameters:
public interface BaseOperation<T, U> {
T execute(U input);
}
public class GetUsersOperation implements BaseOperation<GetUsersResponse, UserInput> {
#Override
public GetUsersResponse execute(UserInput input) {
Date date = input.getDate();
return new GetUsersResponse(date);
}
}
Your abstract class only has one single abstract method: better use an interface. You can implement several interfaces while you can extend only one class.
As already said, the common approach for solving your issue is using a bean holding parameters. But here is another solution, based on a builder approach:
public interface BaseOperation<T> {
public T execute();
}
public class AddOperation implements BaseOperation<Integer> {
private int a, b;
public void setA(int arg){
a = arg ;
return this;
}
public void setB(int arg){
b = arg;
return this;
}
#Override
public Integer execute() {
return a+b ;
}
}
And then use it like this :
new AddOperation().setA(1).setB(2).execute();
You can mix required and optional parameters in this way:
public class MultipleAddOperation implements BaseOperation<Integer> {
private int sum ;
public MultipleAddOperation(int requiredInt){
sum = requiredInt;
}
public void add(int optionalInt){
sum += optionalInt ;
return this;
}
#Override
public Integer execute(){
return sum;
}
}
And so:
new MultipleAddOperation(5).add(1).add(2).execute();
I am using a tool which is generating differrenct classes for different structs I am using
For example it may create two class like this
class TypeSupportImpl {
void callme()
{
System.out.println("I an here");
}
void test()
{
}
}
public class StringReader extends TypeSupportImpl
{
void callme()
{
System.out.println("HelloReader an here");
}
void test()
{
}
public static String get_name() {
String s = "hello";
return s ;
}
}
public class HelloReader extends TypeSupportImpl
{
void callme()
{
System.out.println("HelloReader an here");
}
void test()
{
}
public static String get_name() {
String s = "hello";
return s ;
}
}
Now I want to write a generic wrapper for this class. I want to generic wrapper to behave in such a way that, if user passes Hello as the type it should create object of Helloreader. If the users basses in a String then a StringReader object should be created.
public class TestCode<T > {
//if T= Hello
HelloReader.get_name();
//if T== String
StringReader.get_name()
}
Can you please suggest how to achieve it best way without using reflection.
You can't do it at all, even with reflection. Type erasure means that at runtime, you won't be able to see what the type parameter is, and even if you pass it in as an argument (see the builders for EnumSet), you'd have to use reflection, since static elements are bound to a specific type at compile-time.
I have a question about putting a Java enum in the interface.
To make it clearer, please see the following code:
public interface Thing{
public enum Number{
one(1), two(2), three(3);
private int value;
private Number(int value) {
this.value = value;
}
public int getValue(){
return value;
}
}
public Number getNumber();
public void method2();
...
}
I know that an interface consists of methods with empty bodies. However, the enum I used here needs a constructor and a method to get an associated value. In this example, the proposed interface will not just consist of methods with empty bodies. Is this implementation allowed?
I am not sure if I should put the enum class inside the interface or the class that implements this interface.
If I put the enum in the class that implements this interface, then the method public Number getNumber() needs to return the type of enum, which would force me to import the enum in the interface.
It's perfectly legal to have an enum declared inside an interface. In your situation the interface is just used as a namespace for the enum and nothing more. The interface is used normally wherever you use it.
Example for the Above Things are listed below :
public interface Currency {
enum CurrencyType {
RUPEE,
DOLLAR,
POUND
}
public void setCurrencyType(Currency.CurrencyType currencyVal);
}
public class Test {
Currency.CurrencyType currencyTypeVal = null;
private void doStuff() {
setCurrencyType(Currency.CurrencyType.RUPEE);
System.out.println("displaying: " + getCurrencyType().toString());
}
public Currency.CurrencyType getCurrencyType() {
return currencyTypeVal;
}
public void setCurrencyType(Currency.CurrencyType currencyTypeValue) {
currencyTypeVal = currencyTypeValue;
}
public static void main(String[] args) {
Test test = new Test();
test.doStuff();
}
}
In short, yes, this is okay.
The interface does not contain any method bodies; instead, it contains what you refer to as "empty bodies" and more commonly known as method signatures.
It does not matter that the enum is inside the interface.
Yes, it is legal. In a "real" situation Number would implement Thing, and Thing would probably have one or more empty methods.
In Java, I'd like to have something as:
class Clazz<T> {
static void doIt(T object) {
// ...
}
}
But I get
Cannot make a static reference to the non-static type T
I don't understand generics beyond the basic uses and thus can't make much sense of that. It doesn't help that I wasn't able to find much info on the internet about the subject.
Could someone clarify if such use is possible, by a similar manner? Also, why was my original attempt unsuccessful?
You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.
It doesn't seem like your problem should require using the class's type parameter. If you describe what you are trying to do in more detail, maybe we can help you find a better way to do it.
Java doesn't know what T is until you instantiate a type.
Maybe you can execute static methods by calling Clazz<T>.doit(something) but it sounds like you can't.
The other way to handle things is to put the type parameter in the method itself:
static <U> void doIt(U object)
which doesn't get you the right restriction on U, but it's better than nothing....
I ran into this same problem. I found my answer by downloading the source code for Collections.sort in the java framework. The answer I used was to put the <T> generic in the method, not in the class definition.
So this worked:
public class QuickSortArray {
public static <T extends Comparable> void quickSort(T[] array, int bottom, int top){
//do it
}
}
Of course, after reading the answers above I realized that this would be an acceptable alternative without using a generic class:
public static void quickSort(Comparable[] array, int bottom, int top){
//do it
}
I think this syntax has not been mentionned yet (in the case you want a method without arguments) :
class Clazz {
static <T> T doIt() {
// shake that booty
}
}
And the call :
String str = Clazz.<String>doIt();
Hope this help someone.
It is possible to do what you want by using the syntax for generic methods when declaring your doIt() method (notice the addition of <T> between static and void in the method signature of doIt()):
class Clazz<T> {
static <T> void doIt(T object) {
// shake that booty
}
}
I got Eclipse editor to accept the above code without the Cannot make a static reference to the non-static type T error and then expanded it to the following working program (complete with somewhat age-appropriate cultural reference):
public class Clazz<T> {
static <T> void doIt(T object) {
System.out.println("shake that booty '" + object.getClass().toString()
+ "' !!!");
}
private static class KC {
}
private static class SunshineBand {
}
public static void main(String args[]) {
KC kc = new KC();
SunshineBand sunshineBand = new SunshineBand();
Clazz.doIt(kc);
Clazz.doIt(sunshineBand);
}
}
Which prints these lines to the console when I run it:
shake that booty 'class com.eclipseoptions.datamanager.Clazz$KC' !!!
shake that booty 'class com.eclipseoptions.datamanager.Clazz$SunshineBand' !!!
It is correctly mentioned in the error: you cannot make a static reference to non-static type T. The reason is the type parameter T can be replaced by any of the type argument e.g. Clazz<String> or Clazz<integer> etc. But static fields/methods are shared by all non-static objects of the class.
The following excerpt is taken from the doc:
A class's static field is a class-level variable shared by all
non-static objects of the class. Hence, static fields of type
parameters are not allowed. Consider the following class:
public class MobileDevice<T> {
private static T os;
// ...
}
If static fields of type parameters were allowed, then the following code would be confused:
MobileDevice<Smartphone> phone = new MobileDevice<>();
MobileDevice<Pager> pager = new MobileDevice<>();
MobileDevice<TabletPC> pc = new MobileDevice<>();
Because the static field os is shared by phone, pager, and pc, what is the actual type of os? It cannot be Smartphone, Pager, and
TabletPC at the same time. You cannot, therefore, create static fields
of type parameters.
As rightly pointed out by chris in his answer you need to use type parameter with the method and not with the class in this case. You can write it like:
static <E> void doIt(E object)
Something like the following would get you closer
class Clazz
{
public static <U extends Clazz> void doIt(U thing)
{
}
}
EDIT: Updated example with more detail
public abstract class Thingo
{
public static <U extends Thingo> void doIt(U p_thingo)
{
p_thingo.thing();
}
protected abstract void thing();
}
class SubThingoOne extends Thingo
{
#Override
protected void thing()
{
System.out.println("SubThingoOne");
}
}
class SubThingoTwo extends Thingo
{
#Override
protected void thing()
{
System.out.println("SuThingoTwo");
}
}
public class ThingoTest
{
#Test
public void test()
{
Thingo t1 = new SubThingoOne();
Thingo t2 = new SubThingoTwo();
Thingo.doIt(t1);
Thingo.doIt(t2);
// compile error --> Thingo.doIt(new Object());
}
}
Since static variables are shared by all instances of the class. For example if you are having following code
class Class<T> {
static void doIt(T object) {
// using T here
}
}
T is available only after an instance is created. But static methods can be used even before instances are available. So, Generic type parameters cannot be referenced inside static methods and variables
When you specify a generic type for your class, JVM know about it only having an instance of your class, not definition. Each definition has only parametrized type.
Generics work like templates in C++, so you should first instantiate your class, then use the function with the type being specified.
Also to put it in simple terms, it happens because of the "Erasure" property of the generics.Which means that although we define ArrayList<Integer> and ArrayList<String> , at the compile time it stays as two different concrete types but at the runtime the JVM erases generic types and creates only one ArrayList class instead of two classes. So when we define a static type method or anything for a generic, it is shared by all instances of that generic, in my example it is shared by both ArrayList<Integer> and ArrayList<String> .That's why you get the error.A Generic Type Parameter of a Class Is Not Allowed in a Static Context!
#BD at Rivenhill: Since this old question has gotten renewed attention last year, let us go on a bit, just for the sake of discussion.
The body of your doIt method does not do anything T-specific at all. Here it is:
public class Clazz<T> {
static <T> void doIt(T object) {
System.out.println("shake that booty '" + object.getClass().toString()
+ "' !!!");
}
// ...
}
So you can entirely drop all type variables and just code
public class Clazz {
static void doIt(Object object) {
System.out.println("shake that booty '" + object.getClass().toString()
+ "' !!!");
}
// ...
}
Ok. But let's get back closer to the original problem. The first type variable on the class declaration is redundant. Only the second one on the method is needed. Here we go again, but it is not the final answer, yet:
public class Clazz {
static <T extends Saying> void doIt(T object) {
System.out.println("shake that booty "+ object.say());
}
public static void main(String args[]) {
Clazz.doIt(new KC());
Clazz.doIt(new SunshineBand());
}
}
// Output:
// KC
// Sunshine
interface Saying {
public String say();
}
class KC implements Saying {
public String say() {
return "KC";
}
}
class SunshineBand implements Saying {
public String say() {
return "Sunshine";
}
}
However, it's all too much fuss about nothing, since the following version works just the same way. All it needs is the interface type on the method parameter. No type variables in sight anywhere. Was that really the original problem?
public class Clazz {
static void doIt(Saying object) {
System.out.println("shake that booty "+ object.say());
}
public static void main(String args[]) {
Clazz.doIt(new KC());
Clazz.doIt(new SunshineBand());
}
}
interface Saying {
public String say();
}
class KC implements Saying {
public String say() {
return "KC";
}
}
class SunshineBand implements Saying {
public String say() {
return "Sunshine";
}
}
T is not in the scope of the static methods and so you can't use T in the static method. You would need to define a different type parameter for the static method. I would write it like this:
class Clazz<T> {
static <U> void doIt(U object) {
// ...
}
}
For example:
public class Tuple<T> {
private T[] elements;
public static <E> Tuple<E> of(E ...args){
if (args.length == 0)
return new Tuple<E>();
return new Tuple<E>(args);
}
//other methods
}