Java generation parameters with a common parameter base

I am wondering if there is an elegant solution for this in Java (besides the obvious - declaring another / explicit function) Here is the code:

private static HashMap<String, Integer> nameStringIndexMap 
        = new HashMap<String, Integer>();
private static HashMap<Buffer, Integer> nameBufferIndexMap 
        = new HashMap<Buffer, Integer>();

// and a function
private static String newName(Object object, 
        HashMap<Object, Integer> nameIndexMap){
    ....
}

The problem is that I cannot pass the nameStringIndexMap or nameBufferIndexMap functions to the parameters. I have no idea of ​​a more elegant solution next to executing another function that explicitly wants to use the HashMap <String, Integer> or HashMap <Buffer, Integer> Parameter.

My question is: Can this be done in a more elegant solution / using generics or something like that?

Thank,

Julian

+3
source share
2 answers

You can also create your general function:

private static <E extends Object> String newName(E object, 
        HashMap<E, Integer> nameIndexMap){
    ....
}

, a HashMap<String, Integer> String . , : , Jon , , .

+4

- :

private static String newName(Object object, 
        HashMap<? extends Object, Integer> nameIndexMap) {
    ....
}

( )

private static String newName(Object object, 
        HashMap<?, Integer> nameIndexMap) {
    ....
}

- , , , .

, - , , , Peter, , object . - , . ( , .)

+3

Source: https://habr.com/ru/post/1738632/


All Articles