Java, Subclass return generics of generics |
Here's how to fix the problem:
public class Test {
public static void main(String[] args) {
Human<Blond, Bob> h = new Human<Blond, Bob>();
Blond blond = h.getPerson().getHair();
blond = h.getDirectHair();
}
}
class Human<H extends Hair, T extends Person<H>>{
private T person = null;
public T getPerson() {
return person;
}
public H getDirectHair(){
return person.getHair();
}
}
|
Generics - Using parent class to specify type in generics |
The only way of doing that is with an out generic restriction (which will
make it hard to save objects, but fine to retrieve them), on an interface
(not a class). If you have:
interface IGenericRepository<out T> {...}
then an IGenericRepository<ProductStyle> can be assigned to a
variable of type IGenericRepository<BaseEntity>, since all
ProductStyle are also BaseEntity, and we have restricted ourselves to
covariant / out usage:
IGenericRepository<BaseEntity> tmp =
GetRepo<ProductStyle>(context);
// note that the right-hand-side returns
IGenericRepository<ProductStyle>
...
private IGenericRepository<T> GetRepo(...) {...}
Note, however, that this covariant / out usage makes it impossible to do
things like:
interface IGenericRepository<out T
|
How to reproduce figure through a previously saved figure handle? |
If the graph is still open, you can get the Xdata, Ydata and Zdata by
using:
XYZCell=get(get(get(h,'currentaxes'),'children'),{'xdata','ydata','zdata'});
Or if you don't want a cell:
XData=get(get(get(gcf,'currentaxes'),'children'),'xdata');
YData=get(get(get(gcf,'currentaxes'),'children'),'ydata');
ZData=get(get(get(gcf,'currentaxes'),'children'),'zdata');
If the graph is closed, h is useless - as far as I'm aware there is no way
to reform a graph from a closed figure handle.
Why not use save your variables first?
I1=d1;
I2=d2;
I3=d3;
scatter3(d1,d2,d3,'.');
|
change figure size and figure format in matplotlib |
The first part (setting the output size explictly) isn't too hard:
import matplotlib.pyplot as plt
list1 = [3,4,5,6,9,12]
list2 = [8,12,14,15,17,20]
fig = plt.figure(figsize=(4,3))
ax = fig.add_subplot(111)
ax.plot(list1, list2)
fig.savefig('fig1.png', dpi = 300)
fig.close()
But after a quick google search on matplotlib + tiff, I'm not convinced
that matplotlib can make tiff plots. There is some mention of the GDK
backend being able to do it.
One option would be to convert the output with a tool like imagemagick's
convert.
(Another option is to wait around here until a real matplotlib expert shows
up and proves me wrong ;-)
|
Unable to save matplotlib.figure Figure, canvas is None |
One of the things that plt.figure does for you is wrangle the backend for
you, and that includes setting up the canvas. The way the architecture of
mpl is the Artist level objects know how to set themselves up, make sure
everything is in the right place relative to each other etc and then when
asked, draw them selves onto the canvas. Thus, even though you have set up
subplots and lines, you have not actually used the canvas yet. When you
try to save the figure you are asking the canvas to ask all the artists to
draw them selves on to it. You have not created a canvas (which is
specific to a given backend) so it complains.
Following the example here you need to create a canvas you can embed in
your tk application (following on from your last question)
from matplotlib.backends.backend_
|
Can't figure out how to get rid of a graphic when I figure hit a button |
Rather than creating the objects to be painted within the paintComponent
method itself, maintain a collection of objects that are to be rendered and
loop through that collection each paintComponent call. Then "destroying"
the P2 object is done by simply removing from the collection.
|
which one is better Generics or not Generics in Java? |
You should almost never use the raw form in modern Java. There are a few
places where it's hard not to, but in general it's a bad idea.
Using the raw List and ArrayList types in your second snippet in no way
prevents boxing - it just reduces type safety. In the generic version, you
don't need the cast to int because the compiler knows that the list must
only contain Integer references or null values; in the raw form there's no
compile-time guarantee. There's nothing to stop you adding a completely
different kind of reference - e.g. a string - to the list.
|
C# Generics, what am I doing wrong? |
The Razor parser is interpreting < and > as normal HTML tags.
You can avoid the problem wrapping the call in parenthesis:
@(Model.Products.Grid<Product>(grid=>{
...
}))
You can find additional info here: How to use generic syntax inside a Razor
view file?
|
C# generics with interfaces |
You should define your lists not with the concrete type that implements the
interface, but with the interface:
var lionCage = new ZooCage<IZooAnimal>();
lionCage.Animals = new List<IZooAnimal>();
Then your code will work as expected.
The initial code did not work, because it is not allowed to convert
concrete types to a generalised type (as @default.kramer pointed out
covariance and contravariance).
The solution that i came up is following:
// your ZooCage is still generic
public class ZooCage<T>
{
// but you declare on creation which type you want to contain only!
private Type cageType = null;
public ZooCage(Type iMayContain)
{
cageType = iMayContain;
animals = new List<T>();
}
// check on add if the types ar
|
Generics and ArrayList Help please |
If you want to be able to access Student methods from T instances within
your DatabaseAccess class, you must constraint T's type to be subclasses of
Student:
public class DatabaseAccess<T extends Student> {
// ...
}
By the way, if you make your Student class implement
Comparable<Student> instead of the raw Comparable, your compareTo
method would be easier to write.
|
Confusion about Generics |
So I'm assuming the commented out code is what is not working. The reason
for that is you're trying to access properties of the dictionary and not
the property of a value in the dictionary
this
listBox1.Items.Add(string.Format("File Name :{0} FileSize : {1}",
list.Name, list.Length.));
should be
listBox1.Items.Add(string.Format("File Name :{0} FileSize : {1}",
list[file].Name, list[file].Length));
First you have to retrieve the FileInfo object using the key (in this case
the file name), then you can access the Name and Length properties of that
instance. You list variable is of type dictionary and doesn't have a Name
property. If you're using dot notation on the list like list.Something
you're leaving out a level of indirection.
|
pointers as generics c# |
My suggestion would be to do this in a separate Managed C++ assembly, aka
C++/CLI, where the public .NET API exposes your generically typed interface
and the "unsafe" pointer-related stuff happens in native code.
|
Using methods on Generics |
No, you can't call static methods on generic types - not without
reflection. Aside from anything else, there's no way of constraining a
generic type to have specific static members. The closest to that is the
parameterless constructor constraint.
|
Using generics in Scala |
Functionally? Say why some 3rd-party code has the possibility to load those
classes will do the following:
class ThirdPatyClass(val a: Int) extends SomeClass(a) with ThirdPartyTrait
An instance of Class1[ThirdPartyClass] (and a reified corresponding
method1) could be used where there would be a type bound of the form
[S <: ThirdPartyTrait]
whereas Class2 couldn't.
And, of course, depending what you do within those methods, you could
return an object of type T (or anything that uses T as a bound, e.g.
Class[_ <: T]) in Class1.method1.
In general, with Class1 you're giving the compiler (and the developer) a
possibility to preserve more information on the type of param1, in contrast
with Class2 where you can only preserve the compile-time information that
param1 is an instance o
|
C# Generics with 'Wildcards' |
You need to make a contravariant generic interface IRule<TSource, in
TSelected> and make a list of that, where in addition TSelected is going
to be constrained to some meaningful class. Constraining to any reference
type as in your existing code will compile, but you won't be able to do
anything meaningful with anything that has to do with TSelected.
At this time there is no other way to use variant generics (unless of
course you go into reflection mode with List<dynamic> or something
equivalent), so if this solution does not work for you you will need to
redesign.
|
An elegant way to do this? May be generics? |
Define a generic interface like this:
public interface ITransactionable<T>
where T : Transaction
{
T CreateTransaction();
}
And decorate your BussinessService and Product as:
public class BussinessService :
ITransactionable<ServiceCharge>
{
public T CreateTransaction()
{
return new ServiceCharge(this);
}
}
public class Product :
ITransactionable<Sale>
{
public T CreateTransaction()
{
return new Sale(this);
}
}
Now your generic method can be defined as:
private void CreateInstance<T>(ITransactionable<T> element)
{
Transaction transaction = element.CreateTransaction();
...
}
|
Correct use of Generics |
You're getting a warning because you're casting to the raw type
LazyRetiDataModel. I would recommend the following instead:
if (lazyModel != null) {
((LazyRetiDataModel<Rete>)lazyModel).setFilters(mappa);
}
Typically, this would result in an unchecked cast warning, but this is
actually an exception to that rule since the compiler already knows the
generic type is Rete.
Note that I also agree with Luiggi Mendoza's comment about
LazyRetiDataModel<T> extends LazyDataModel<Rete> probably being
a typo - you want LazyRetiDataModel<T> extends
LazyDataModel<T>.
|
Generics and interface // do I have to use them together? |
This is the main principle of OOP. You're working with objects and objects
have behaviors (methods).
Every method knows what objects it is working with. For example, your
method compares 2 numbers. If you pass 1 number and 1 Array of Strings it
won't be able to compare them.
You don't have to use interface as upperbound in your example.It can be
your class and in case you have 2 classes that have similar behavior then
you create an interface and change your method above to use that interface.
Also, by Java Code Conventions interface name should start from capital
letter.
|
Should I use generics to solve this issue? |
Two solutions, you decide:
1. make another interface with boolean return type
2. change the return type to boolean (recommended as you can always return
true if in fact info were stored)
|
C# Using generics and interface implementation |
The problem is that Form<Field> implements IForm<Field> but not
IForm<IField>. You cannot use an inherited class (or interface) as a
generic parameter unless it is marked as covariant with the out identifier.
However, marking your interface as covariant will restrict the usage
significantly (basically making in an "output-only" interface like
IEnumerable) so it may not work for you.
One way to get it to work is to make TestMethod generic as well:
public static void TestMethod<T>(IForm<T> form) where T:IField
{
int i = 1;
i = i * 5;
}
|
Realizing polymorphism with Generics in C# |
It is possible to achieve this with generics as such:
First, you want to create Generic classes for your parser and repository:
public class Parser<T> : IParser<T>
{
IList<T> ParseDataTableToList(DataTable dataTable,
object o)
{
var list = new List<T>();
//Your parsing logic can go:
//1) Here(using reflection, for example) or
//2) in the constructor for Motor/Switchboard object,
//in witch case they will take a reader or row object
return list;
}
}
public class Repo<T> : IInsertOrUpdateList<T>
{
void InsertOrUpdate(IList<T> list)
{
//.
|
Java JComboBox Generics |
You can specify a language target level and a bytecode target level. This
way you can use all the language feature of a certain version and compile
it against a specific vm version. I tested your example with the following
setting: Language level 7, bytecode version 6 and it compiles just fine.
But you still would have to compile it against a jdk 7, so the compiler
knows that the JCombobox is generic.
|
Java generics: Is this safe enough? |
Generics use the class type of the first T type argument. Adding the new
Class<T> does not add any more safeness. In fact, you are now
requiring that you have know what class to put in the list of arguments,
which can be cumbersome.
|
Advantage of TypeScript generics |
The advantage for generics on Arrays is "under the hood". Both annotations
in your question are identical as far as TypeScript is concerned.
The advantage of generics is that you can reuse code, rather than copy and
pasting the code to work for different types or using a dynamic type where
you don't intend to use dynamic behaviour.
For example, the Array interface can be declared just once:
interface Array<T> {
pop() : T;
}
Rather than having to have:
interface Array {
pop() : any;
}
Or (for each type)
interface ArrayOfStrings {
pop() : string;
}
|
C# Generics - Lists of collections |
I would contend that you just need a single list:
public DeviceCollection<Device> Devices { get; private set; }
and then you can return specific types with Switches for example:
public IEnumerable<Switch> Switches
{
get
{
return this.Devices.OfType<Switch>();
}
}
and so now enumerate just looks like this:
protected override IEnumerator<Device> enumerate()
{
foreach (var d in Devices)
{
yield return d;
}
}
|
Generics issue with Java |
Specify the generics type as
Map<String, Object> data = this.aub.getData();
data.put("ip_macs", new LinkedList<Object>()); // Compiles
When you say Map<String, ? extends Object> it means a Map whose key
is of type String and the value extends Object but its type is unknown ?.
Since, the type is not known it's unsafe to insert a LinkedList object
there.
Basically, the compiler is trying to prevent this:
Map<String, String> mapOfStrings = new HashMap<String,
String>();
mapOfStrings.add("string", "value");
Map<String, ? extends Object> map = mapOfStrings; // Compiles
map.add("string", 1); // ERROR!
If this was allowed, you just circumvented the type safety offered by
generics.
|
Java Generics and overridding |
The method function2 is not generic. It returns a Bar<Foo>.
Subclasses may return subclasses of return types in overridden methods.
This is called a covariant return type.
But Bar<F> is not a subclass of Bar<Foo>, even if F subclasses
Foo - generics are not covariant in Java (arrays are, though).
My IDE actually warns me about function1 too: Unchecked overriding: return
type requires unchecked conversion. I believe this is only a warning
because of the sole existence of a generic type in base class and type
erasure. I'd say you're operating on non-generic Bars anyway here..
|
Deciphering Generics Syntax |
<E extends CharSequence>
tells that E will be a subtype of CharSequence. This tells the compiler
that the type argument that will be passed to this method will either be a
CharSequence or a sub type of that type. This type of bound is known as a
parameter bound. I have written an article on this topic, you can check it
out if you like.
List<? super E>
tells that this method will return a List of elements whose type will be
either E or its super type.
So, all of the following types could be returned from your doIt method -
// trivial one.
return new ArrayList<E>();
// If F is a super type of E, then the following line is valid too.
return new ArrayList<F>();
// The following will also be valid, since Object is a super type of all
// other types.
return new
|
Conversion of arrays with generics |
Generics add stability to your code by making more of your bugs
detectable at compile time.
This is a part from the link that i have given, thought that as important,
so i am posting that here
This is a small excerpt from the definitions of the interfaces List
and Iterator in package java.util:
public interface List <E> {
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E> {
E next();
boolean hasNext();
}
This code should all be familiar, except for the stuff in angle
brackets. Those are the declarations of the formal type
parameters of the interfaces List and Iterator.
Type parameters can be used throughout the generic declaration, pretty
much where you would use ordinary types.
We know the invocations
|
What is the difference between '&' and ',' in Java generics? |
<T extends MyClass & Serializable>
This asserts that the single type parameter T must extend MyClass and must
be Serializable.
<T extends MyClass , Serializable>
This declares two type parameters, one called T (which must extend MyClass)
and one called Serializable (which hides java.io.Serializable — this is
probably what the warning was about).
|
Dart, constraints on Generics? |
You can specify type constraints like this :
class StackPanel<TBase extends SomeType> extends Panel<TBase> {
}
The language specification says :
A type parameter T may be suffixed with an extends clause that specifies
the upper bound for T. If no extends clause is present, the upper bound is
Object. It is a static type warning if a type parameter is a supertype of
its upper bound. The bounds of type variables are a form of type annotation
and have no effect on execution in production mode.
|
Configuring AutoMapper without Generics |
Currently the NullSubstitute configuration is not available on the
IMappingExpression interface which is used when you are using the non
generic version of CreateMap.
There is no limitation which is preventing Automapper to have this method
on the IMappingExpression so currently this is just not supported.
You have three options:
Create an issue on Github and wait until it is implemented
Fork the project and implement the method yourself. It is very easy you can
use the generic version as an example.
Or if you want a quick but very dirty solution. With reflection you can get
the underlaying PropertyMap from the configuration and call the
SetNullSubstitute method on it:
Mapper.CreateMap(typeof(Source), typeof(Dest))
.ForMember("Value", opt =>
{
FieldInfo fiel
|
How to apply Generics methods |
public DateTime ExportResultsToCsv<T>(string filePath, string
HeaderLine, List<T> data)
{
engine = new FileHelperEngine(typeof(T)) { HeaderText = HeaderLine };
engine.WriteFile(filePath, data);
return DateTime.Now;
}
For more info on generics see this article on MSDN
|
StyleCop SA1402 and Generics |
They are several nameing convension. It seems the most popular is
Operation[TType].cs
Operation[T,TType].cs
Operation[T1, T2, TType].cs
But you can also use something more classic, like
Operation`1.cs
Operation`2.cs
Operation`3.cs
(see Convention for Filenames of Generic Classes)
|
Confused about this generics use case |
That's the syntax for generic methods.
The <T extends Bean> in the method declaration tells us that the
method uses generics, and you can use T inside the method body as a type.
In your code, T has no meaning.
|
vb.net extending a class with generics |
is it possible to extend different classes with the same generic class?
Generics isn't some kind of "workaround" for a lack of multiple
inheritance, no. Your class C doesn't derive from A - it just means that
the T in B(Of T) would be A in the context of C.
Which instance of A would you expect TestA() to be called on? Creating an
instance of C certainly doesn't create an instance of A...
The fact that B(Of T) doesn't use T anywhere should be a warning signal -
types which are generic but never use their generic type parameters are
generally problematic.
It's hard to know exactly how to help you solve your real problem without
more details, but you can't add a common base class in like this, when you
also need to derive from other types which aren't under your control.
Perhaps exte
|
Mockito casting to generics |
You do not have an explicit relationship between T and SomeType. Therefore,
how could SomeType be cast to T? For this to work T MUST be a super class
of SomeType. This is not a Mockito issue, just straight Java.
According to the test I would have expected your method to look like this:
SomeTypeCollection<SomeType> someTypeCollection = ...
SomeType currentObject = null;
while( ( currentObject = (SomeType) someTypeCollection.next() ) != null )
{...}
or
public <T super SomeType> void method(){
SomeTypeCollection<SomeType> someTypeCollection = ...
TcurrentObject = null;
while( ( currentObject = (T) someTypeCollection.next() ) != null ) {...}
}
|
C# where inside a where in Templates / Generics |
This will compile:
public void SomeMethod<TBase, TChild>()
where TBase : class, ISomeInterface<TChild>, new()
where TChild : IAnotherInterface // No problem is here.
{
}
internal interface IAnotherInterface
{
}
internal interface ISomeInterface<TChild>
{
}
|
Generics method overriding 8 |
You cannot override a method declared as
void say(List<? extends Number> list) // A
with
void say(List<Number> list) // B
simply because the types are not equivalent. For example,
List<Integer> matches List<? extends Number> but not
List<Number>, so
List<Integer> integers = Arrays.<Integer>asList(1, 2, 3);
a.say(integers); // is valid assuming signature A
b.say(integers); // does not compile
(see this question for details about generics, wildcards, and type
relationships). If the compiler did allow you to override the way you want
to, then the following would be possible:
class A {
void say(List<? extends Number> numbers) { }
}
class B extends A {
void say(List<Number> numbers) { numbers.add(Double.v
|
Generics vs. Method Overloading |
Your second method expects the generic type of expectedItems (? extends T)
to be a subtype of the generic type of found (T).
In your third method, there is no subtype relationship between the two
generic types. They both extend T but could be siblings for example.
So the second method can't be called.
Example: imagine you call the third method with those types:
containsAtLeast(Collection<Integer> e, Collection<String> f)
So the T in your third method is Object. And your first method is called
with T = Object too.
|