1

Can anyone please explain me below code

 public <T extends Emp> void foo(ArrayList<T> list) {
    list.add(list.remove(0)); // (cycle front element to the back)
}

I am trying to understand how Generics will apply on void return type. Note: i have changed the code now it is not giving any error.

7
  • 1
    It does not apply to the void. It's for the ArrayList. Commented Dec 5, 2016 at 10:50
  • 2
    This code will not compile. You're trying to add a String to an ArrayList<T> where T is definitely not a string. Commented Dec 5, 2016 at 10:50
  • They won't apply to void. Commented Dec 5, 2016 at 10:52
  • i have modified the code.. i was trying to understand generics at void return type. Commented Dec 5, 2016 at 10:52
  • @GurwinderSingh its not giving any error. its compile fine.. Commented Dec 5, 2016 at 10:53

2 Answers 2

4

I am trying to understand how generics will apply on void return type.

This is only a syntax. Generics do not apply to void return type, they apply to the method as a whole.

The name and restrictions on the generic parameter need to go somewhere in the text of your program. In a class declaration they follow the class name in angular brackets. In a generic method declaration they follow the accessibility designator public, and precedes the return type void.

One could easily imagine an alternative placement of generic types, such as

public void foo<T extends Emp>(ArrayList<T> list)  // Imaginary syntax

or even

public void foo(ArrayList<T> list) <T extends Emp> // Imaginary syntax

but Java designers decided on the placement before the return type designator.

Sign up to request clarification or add additional context in comments.

Comments

2

Generics won't be applied to void.

If you say that the type is <T extends Emp>, you are saying, that any subtype of Emp can be applied in place of T.

In your code, You can use <T> instead of <T extends Emp> as you aren't doing anything with Emp

public <T> void foo(ArrayList<T> list) {
    list.add(list.remove(0)); // (cycle front element to the back)
}

Regarding how it'll work, the type will be provided by you when you use this method and at compile time, java will place required casts automatically. So, if you are using this:

ArrayList<String> list = new ArrayList<>();
// Add some items into list
foo(list);

in that case, your foo() method will find out that type <T> is String and so, will behave something like:

public void foo(ArrayList<String> list) {
    list.add((String)(list.remove(0)));
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.