Saturday, 15 August 2015

java - How can I make different captures of a wildcard compatible? -



java - How can I make different captures of a wildcard compatible? -

i'm trying create generic class 1 type parameter, class myclass<e>, has class variable of sec generic class 2 type parameters, secondclass<v, e>. since code doesn't matter type of v is, declare type of variable secondclass<?, e> var. @ point in implementation of myclass phone call method on var returns v, public v foo(e e), , pass object of type v method of var, public int bar(v v). however, doesn't compile because of reasons vaguely understand, believe explained in here.

apparently, capture-of-? returned foo different the capture-of-? required bar. why? whatever actual type of v is, must same both methods, since invoked on same instance. missing here?

ultimately, know this: need alter in order create code compile, without adding v type parameters of myclass? (i don't want enforce users of myclass specify type of v since shouldn't matter)

to give more concrete example, here's simplified version of i'm working on. may have guessed type parameters, concerns graphs. myclass translates edgepainter , secondclass translates graph. code, compile error in first line of edgepainter.getcolor(e).

class graph<v, e> { public v gettarget(e edge) { homecoming null; } public int getindegree(v vertex) { homecoming 0; } } class edgepainter<e> { private static final color color_for_many_edges = color.red; private static final color color_for_few_edges = color.blue; private graph<?, e> graph; public edgepainter(graph<?, e> agraph) { graph = agraph; } public color getcolor(e edge) { // compiler says: // method getindegree(capture#3-of ?) in type // graph<capture#3-of ?,e> not applicable arguments // (capture#4-of ?) int grade = graph.getindegree(graph.gettarget(edge)); if (degree > 10) homecoming color_for_many_edges; else homecoming color_for_few_edges; } }

you can capture wildcard invoking generic method.

public color getcolor(e edge) { homecoming getcolorinternal(graph, edge); } private <x> color getcolorinternal(graph<x, e> g, e e) { int grade = g.getindegree(g.gettarget(e)); // ... }

this typical scenario. need type argument implementation, want hide api users. if many methods affected can helpful define separate, perhaps nested, class edgepainterinternal. internal implementation has sec type parameter g , publicly visible implementation edgepainter delegates all calls instance of edgepainterinternal.

java generics

No comments:

Post a Comment