Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use nested generics in Java?

I was trying to do something like:


public class MyClass <A, B, C <A, B> > {
  ...
}

But Eclipse highlights "B," and says "unexpected , expected extends". What gives? Are nested generics not allowed?

like image 697
Anonymous Avatar asked Sep 17 '11 00:09

Anonymous


People also ask

What is not allowed for generics Java?

To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.

Can a generic class have multiple generic parameters Java?

A Generic class can have muliple type parameters.

Can Java generics be applied to primitive types?

Using generics, primitive types can not be passed as type parameters. In the example given below, if we pass int primitive type to box class, then compiler will complain. To mitigate the same, we need to pass the Integer object instead of int primitive type.

Can generic types be inherited Java?

Generics also provide type safety (ensuring that an operation is being performed on the right type of data before executing that operation). Hierarchical classifications are allowed by Inheritance. Superclass is a class that is inherited. The subclass is a class that does inherit.


2 Answers

It's because you haven't defined C as a type that is itself typed with 2 type parameters.
Try something like this:

public class MyClass <A, B, C extends Map<A, B>> {
    // This compiles
}
like image 199
Bohemian Avatar answered Sep 28 '22 19:09

Bohemian


If your template parameters don't share share a class hierarchy, you can use an interface.

For example:

interface IConverter<TFrom, TTo>
{
    TTo convert(TFrom from);
}

class IntToStringConverter implements IConverter<Integer, String>
{
    public String convert(Integer from)
    {
        return "This is a string: " + from.toString();
    }
}

class ConverterUser<TConverter extends IConverter<TFrom, TTo>, TFrom, TTo>
{
    public ConverterUser()
    {
    }

    private List<TConverter> _converter2;

    private TConverter _converter;

    public void replaceConverter(TConverter converter)
    {
        _converter = converter;
    }

    public TTo convert(TFrom from)
    {
        return _converter.convert(from);
    }
}

class Test
{
    public static void main(String[] args)
    {
        ConverterUser<IntToStringConverter, Integer, String> converterUser =
            new ConverterUser<IntToStringConverter, Integer, String>();

        converterUser.replaceConverter(new IntToStringConverter());

        System.out.println(converterUser.convert(328));
    }
}
like image 30
Dan Cecile Avatar answered Sep 28 '22 20:09

Dan Cecile