0

I want to create a generic method which takes a single parameter of supertype of single type by using super keyword.Is there any way to do so?

I want to do something like this, which is a s very basic requirement.Can somebody please provide me a roundabout since compiler doesnt allow me to define type using lowerbound(super)

public <T super LinkedHashSet> void check(T t){

    }
Kumar Abhinav
  • 6,565
  • 2
  • 24
  • 35
  • What are you exactly trying to achieve? Looks like it should be `public void check(Set> set)`. – Luiggi Mendoza Mar 12 '14 at 00:10
  • 2
    Object is a supertype of LinkedHashSet and any object is an Object. Not sure I understand what you are trying to achieve... – assylias Mar 12 '14 at 00:11
  • @LuiggiMendoza I want that the parameter should be of type LinkedHashSet or it supertype – Kumar Abhinav Mar 12 '14 at 00:11
  • My question is **why**. It is not clear from your content, and by your intentions, you could pass `new Object()` as parameter and will compile fine. – Luiggi Mendoza Mar 12 '14 at 00:12
  • @LuiggiMendoza yes it should work fine.But It should also not allow me to pass a type of say String or Integer or subtype of LinkedHashmap.It can be only LinkedHashMap,HashMap,AbstractMap or Object – Kumar Abhinav Mar 12 '14 at 00:14
  • If i write this method in terms of Object,I can pass any class.But I want the method to accept a parameter of its own type or supertype – Kumar Abhinav Mar 12 '14 at 00:18
  • You may want to consider using an Interface (or even a marker interface). Again, let us know what you are trying to do (not how you want to do it). – ErstwhileIII Mar 12 '14 at 00:19
  • I want to have a method which takes a parameter and restrict its type to a super class of a particualr type.I hope I am clear – Kumar Abhinav Mar 12 '14 at 00:21
  • @ErstwhileIII Is there in way in generics we can do it by using super keyword like ?? – Kumar Abhinav Mar 12 '14 at 00:35
  • @AbhinavKumar *Why* do you want to do this? There may be other, cleaner approaches. Can you give us more specifics about the type of situation you would use this in, perhaps examples of how you intend to use `check`? Java doesn't really keep information about what types *inherit* from a given type. Also, you would be limited to only using methods of `Object`; so why not just operate on `Object`s? – Jason C Mar 12 '14 at 00:48
  • @AbhinavKumar *It can be only LinkedHashMap,HashMap,AbstractMap* -- What about accepting `` or `` instead? – Jason C Mar 12 '14 at 00:52
  • http://stackoverflow.com/questions/4902723/why-cant-a-java-type-parameter-have-a-lower-bound – jaco0646 Mar 12 '14 at 02:16

0 Answers0