Skip to content
Advertisement

Tag: generics

How to write a method that takes in a List of Integer, Float, Double and calculate the average?

I am trying to write a method that takes in a list of numeric values – eg List<Integer>, List<Float>, List<Double> etc – and give me the average. These are the errors I get: Operator ‘+’ cannot be applied to ‘capture<? extends java.lang.Number>’, ‘capture<? extends java.lang.Number>’ Answer OptionalDouble average() Where, OptionalDouble is a container object which may or may not contain

Instantiate generic classes with different constructor arguments

I have two similar classes, Foo and Bar And I’ve got two methods in another class that creates a Set of Foo (1st method) and Bar (2nd method) and are pretty much the same. The first one: And the second one: As you can see, both methods are pretty much the same so I thought I could use generics to

Passing generic types inner class

Here is following example: Is there a way just to pass the generic <String> one time? Actually the inner class should already know its type. Answer That is a limitation of the Java compiler. Although it looks obvious in this case that the type parameter must be String, inferring that is not as easy as it seems to be: The

Java generics input type vs returned type

I’m learning about generics and am slightly confused. I’m confused about the difference between the input type and returned type for a class using generics. We are pushing in an int value of 0 and 2. But the first print statement will print “Integer”. If the stack is declared with Integer as its generic type, why are we able to

Generic Method in Java with out parameters

I am trying to implement something similar to EventBus implemented in eshopOnContainers. Is it Possible to define a method like this in java & read the meta data about T and TH at runtime ? There can be multiple classes extending IntegrationEvent(e.g. PriceChangedEvent) & we should be able to Identify the exact class name at runtime. Answer You can pass

DownCasting in generics in java

I am stuck in generics downcasting. Because I learn type erasure. When code compiles all parameterized types are converted to the upper bound if the bound is not defined then it changes to object. Gen Class GenDemo Class String str = strob.getob(); is converted to String implictly. how JVM converted strob.getob() to String. From where JVM found the strob.getob() is

Advertisement