Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding generic methods

Tags:

java

generics

I want to call the following method :

<C extends Iterable<R>> C as(Class<C> container)

(Anyone familiar with spring-data-neo4j will recognize this as a method of the EndResult class).

I'm not entirely comfortable with generics yet, and I don't understand how to call this method.

ArrayList<Point> pointlist = neo4jtemplate.findAll(Line.class).as( ?? );

the findAll() method returns an iterable of basic Neo4j "nodes", and chaining the .as(). method to it converts that result into an iterable of another type. If I wanted to convert it to an iterable of (for example)Point objects, how would I call this method?

like image 414
drew moore Avatar asked Apr 25 '26 07:04

drew moore


1 Answers

The parameter container must be a Class object of a class that implements the Iterable interface for the type R. For example:

neo4jtemplate.findAll(Line.class).as(MyClassThatIteratesOverTypeR.class);

If the Iterable type is Point, perhaps:

class PointIterator implements Iterable<Point> {
    // you would have to implement all the method of Iterator
}

or simply:

class PointIterator extends ArrayList<Point> { } // That's all you need

then:

neo4jtemplate.findAll(Line.class).as(PointIterator.class);

Note that generics don't allow you to create a typed literal:

neo4jtemplate.findAll(Line.class).as(ArrayList<R>.class); // can't do this
like image 110
Bohemian Avatar answered Apr 27 '26 21:04

Bohemian



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!