Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could I convert this method using generics?

Tags:

java

generics

I currently have the following method in a class which I hope I can push to a superclass since I will have a few other classes which will need similar functionality.

public long convertToLong(EnumSet<SomeTypeHere> es) {

  long a = 0;

  for(SomeTypeHere sth : es) {
     a += sth.someLongProperty();

  }
}

It would be great if I can do this, I've never really used java generics before other than with collections.

like image 328
Blankman Avatar asked Aug 22 '26 14:08

Blankman


2 Answers

You will need to put a bound on the generic type. If the class which contains convertToLong is parameterized on the same type, you can put the bound there:

import java.util.*;
public class GenericTest<C extends GenericTest.HasLongProperty> {
    static interface HasLongProperty {
        long someLongProperty();
    }
    public long convertToLong(Collection<C> es) {
        long a = 0;
        for(C sth : es)
            a += sth.someLongProperty();
        return a;
    }
}

Or if the class which contains convertToLong is not generic, you can put the bound in the declaration of that one method alone:

import java.util.*;
public class GenericTest {
    static interface HasLongProperty {
        long someLongProperty();
    }
    public <C extends GenericTest.HasLongProperty> long convertToLong(Collection<C> es) {
        long a = 0;
        for(C sth : es)
            a += sth.someLongProperty();
        return a;
    }
}
like image 78
Alex D Avatar answered Aug 24 '26 04:08

Alex D


I think you want something like this:

public <T extends SomeType> long convertToLong(Collection<T> es) {

    long a = 0;

    for(T sth : es) {
       a += sth.someLongProperty();

    }
    return a;
  }

This says that you can pass in a Set of type T where T can be any subclass of SomeType and SomeType has the function someLongProperty.

like image 30
Peter Avatar answered Aug 24 '26 04:08

Peter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!