Search Results

Search found 1008 results on 41 pages for 'generics'.

Page 7/41 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • Why prefer a wildcard to a type discriminator in a Java API (Re: Effective Java)

    - by Michael Campbell
    In the generics section of Bloch's Effective Java (which handily is the "free" chapter available to all: http://java.sun.com/docs/books/effective/generics.pdf), he says: If a type parameter appears only once in a method declaration, replace it with a wildcard. (See page 31-33 of that pdf) The signature in question is: public static void swap(List<?> list, int i, int j) vs public static void swap(List<E> list, int i, int j) And then proceeds to use a static private "helper" function with an actual type parameter to perform the work. The helper function signature is EXACTLY that of the second option. Why is the wildcard preferable, since you need to NOT use a wildcard to get the work done anyway? I understand that in this case since he's modifying the List and you can't add to a collection with an unbounded wildcard, so why use it at all?

    Read the article

  • Is `List<Dog>` a subclass of `List<Animal>`? Why aren't Java's generics implicitly polymorphic?

    - by froadie
    I'm a bit confused about how Java generics handle inheritance / polymorphism. Assume the following hierarchy - Animal (Parent) Dog - Cat (Children) So suppose I have a method doSomething(List<Animal> animals). By all the rules of inheritance and polymorphism, I would assume that a List<Dog> is a List<Animal> and a List<Cat> is a List<Animal> - and so either one could be passed to this method. Not so. If I want to achieve this behavior, I have to explicitly tell the method to accept a list of any subset of Animal by saying doSomething(List<? extends Animal> animals). I understand that this is Java's behavior. My question is why? Why is polymorphism generally implicit, but when it comes to generics it must be specified?

    Read the article

  • Help with Java Generics: Cannot use "Object" as argument for "? extends Object"

    - by AniDev
    Hello, I have the following code: import java.util.*; public class SellTransaction extends Transaction { private Map<String,? extends Object> origValueMap; public SellTransaction(Map<String,? extends Object> valueMap) { super(Transaction.Type.Sell); assignValues(valueMap); this.origValueMap=valueMap; } public SellTransaction[] splitTransaction(double splitAtQuantity) { Map<String,? extends Object> valueMapPart1=origValueMap; valueMapPart1.put(nameMappings[3],(Object)new Double(splitAtQuantity)); Map<String,? extends Object> valueMapPart2=origValueMap; valueMapPart2.put(nameMappings[3],((Double)origValueMap.get(nameMappings[3]))-splitAtQuantity); return new SellTransaction[] {new SellTransaction(valueMapPart1),new SellTransaction(valueMapPart2)}; } } The code fails to compile when I call valueMapPart1.put and valueMapPart2.put, with the error: The method put(String, capture#5-of ? extends Object) in the type Map is not applicable for the arguments (String, Object) I have read on the Internet about generics and wildcards and captures, but I still don't understand what is going wrong. My understanding is that the value of the Map's can be any class that extends Object, which I think might be redundant, because all classes extend Object. And I cannot change the generics to something like ? super Object, because the Map is supplied by some library. So why is this not compiling? Also, if I try to cast valueMap to Map<String,Object>, the compiler gives me that 'Unchecked conversion' warning. Thanks!

    Read the article

  • Generics : List<? extends Animal> is same as List<Animal>?

    - by peakit
    Hi, I am just trying to understand the extends keyword in Java Generics. List<? extends Animal> means we can stuff any object in the List which IS A Animal then won't the following also mean the same thing: List<Animal> Can someone help me know the difference between the above two? To me extends just sound redundant here. Thanks!

    Read the article

  • C# 4.0: Covariance And Contravariance In Generics

    - by Paulo Morgado
    C# 4.0 (and .NET 4.0) introduced covariance and contravariance to generic interfaces and delegates. But what is this variance thing? According to Wikipedia, in multilinear algebra and tensor analysis, covariance and contravariance describe how the quantitative description of certain geometrical or physical entities changes when passing from one coordinate system to another.(*) But what does this have to do with C# or .NET? In type theory, a the type T is greater (>) than type S if S is a subtype (derives from) T, which means that there is a quantitative description for types in a type hierarchy. So, how does covariance and contravariance apply to C# (and .NET) generic types? In C# (and .NET), variance applies to generic type parameters and not to the resulting generic type. A generic type parameter is: covariant if the ordering of the generic types follows the ordering of the generic type parameters: Generic<T> = Generic<S> for T = S. contravariant if the ordering of the generic types is reversed from the ordering of the generic type parameters: Generic<T> = Generic<S> for T = S. invariant if neither of the above apply. If this definition is applied to arrays, we can see that arrays have always been covariant because this is valid code: object[] objectArray = new string[] { "string 1", "string 2" }; objectArray[0] = "string 3"; objectArray[1] = new object(); However, when we try to run this code, the second assignment will throw an ArrayTypeMismatchException. Although the compiler was fooled into thinking this was valid code because an object is being assigned to an element of an array of object, at run time, there is always a type check to guarantee that the runtime type of the definition of the elements of the array is greater or equal to the instance being assigned to the element. In the above example, because the runtime type of the array is array of string, the first assignment of array elements is valid because string = string and the second is invalid because string = object. This leads to the conclusion that, although arrays have always been covariant, they are not safely covariant – code that compiles is not guaranteed to run without errors. In C#, the way to define that a generic type parameter as covariant is using the out generic modifier: public interface IEnumerable<out T> { IEnumerator<T> GetEnumerator(); } public interface IEnumerator<out T> { T Current { get; } bool MoveNext(); } Notice the convenient use the pre-existing out keyword. Besides the benefit of not having to remember a new hypothetic covariant keyword, out is easier to remember because it defines that the generic type parameter can only appear in output positions — read-only properties and method return values. In a similar way, the way to define a type parameter as contravariant is using the in generic modifier: public interface IComparer<in T> { int Compare(T x, T y); } Once again, the use of the pre-existing in keyword makes it easier to remember that the generic type parameter can only be used in input positions — write-only properties and method non ref and non out parameters. Because covariance and contravariance apply only to the generic type parameters, a generic type definition can have both covariant and contravariant generic type parameters in its definition: public delegate TResult Func<in T, out TResult>(T arg); A generic type parameter that is not marked covariant (out) or contravariant (in) is invariant. All the types in the .NET Framework where variance could be applied to its generic type parameters have been modified to take advantage of this new feature. In summary, the rules for variance in C# (and .NET) are: Variance in type parameters are restricted to generic interface and generic delegate types. A generic interface or generic delegate type can have both covariant and contravariant type parameters. Variance applies only to reference types; if you specify a value type for a variant type parameter, that type parameter is invariant for the resulting constructed type. Variance does not apply to delegate combination. That is, given two delegates of types Action<Derived> and Action<Base>, you cannot combine the second delegate with the first although the result would be type safe. Variance allows the second delegate to be assigned to a variable of type Action<Derived>, but delegates can combine only if their types match exactly. If you want to learn more about variance in C# (and .NET), you can always read: Covariance and Contravariance in Generics — MSDN Library Exact rules for variance validity — Eric Lippert Events get a little overhaul in C# 4, Afterward: Effective Events — Chris Burrows Note: Because variance is a feature of .NET 4.0 and not only of C# 4.0, all this also applies to Visual Basic 10.

    Read the article

  • Need help understanding Generics, How To Abstract Types Question.

    - by kmacmahon
    I could use some really good links that explain Generics and how to use them. But I also have a very specific question, relater to working on a current project. Given this class constructor: public class SecuredDomainViewModel<TDomainContext, TEntity> : DomainViewModel<TDomainContext, TEntity> where TDomainContext : DomainContext, new() where TEntity : Entity, new() And its creation this way: DomainViewModel d; d = new SecuredDomainViewModel<MyContext, MyEntityType>(this.context, selectedProtectedItem); Assuming I have 20 EntityTypes within MyContext, is there any easier way to call the constructor without a large switch statement? Also, since d is DomainViewModel and I want to access methods for SecuredDomainViewModel, it seems I need to do this: if (((SecuredDomainViewModel<MyContext, MyEntityType>)d).IsBusy) But again "MyEntityType" could actually be one of 20 types. Is there anyway to write these types of statements where MyEntityType is returned from some sort of Reflection?

    Read the article

  • Need help understanding Generics, How To Abstract Types Question.

    - by kmacmahon
    I could use some really good links that explain Generics and how to use them. But I also have a very specific question, relater to working on a current project. Given this class constructor: public class SecuredDomainViewModel<TDomainContext, TEntity> : DomainViewModel<TDomainContext, TEntity> where TDomainContext : DomainContext, new() where TEntity : Entity, new() public SecuredDomainViewModel(TDomainContext domainContext, ProtectedItem protectedItem) : base(domainContext) { this.protectedItem = protectedItem; } And its creation this way: DomainViewModel d; d = new SecuredDomainViewModel<MyContext, MyEntityType>(this.context, selectedProtectedItem); Assuming I have 20 different EntityTypes within MyContext, is there any easier way to call the constructor without a large switch statement? Also, since d is DomainViewModel and I later need to access methods from SecuredDomainViewModel, it seems I need to do this: if (((SecuredDomainViewModel<MyContext, MyEntityType>)d).CanEditEntity) But again "MyEntityType" could actually be one of 20 diffent types. Is there anyway to write these types of statements where MyEntityType is returned from some sort of Reflection?

    Read the article

  • Why Is It That Generics Constraint Can't Be Casted to Its Derived Type?

    - by Ngu Soon Hui
    It is quite puzzling to find out that Generics Constraint Can't Be Casted to Its Derived Type. Let's say I have the following code: public abstract class BaseClass { public int Version { get { return 1; } } public string FixString { get; set; } public BaseClass() { FixString = "hello"; } public virtual int GetBaseVersion() { return Version; } } public class DeriveClass: BaseClass { public new int Version { get { return 2; } } } And guess what, this method will return a compilation error: public void FreeConversion<T>(T baseClass) { var derivedMe = (DeriveClass)baseClass; } I would have to cast the baseClass to object first before I can cast it to DerivedClass. Seems to me pretty ugly. Why this is so?

    Read the article

  • What's the purpuse behind wildcards and how are they different from generics?

    - by Nazgulled
    Hi, I never heard about wildcars until a few days ago and after reading my teacher's Java book, I'm still not sure about what's it for and wwhy would I need to use it. Let's say I have a super class Animal and few sub classes like Dog, Cat, Parrot, etc... Now I need to have a list of animals, my first thought would be something like: List<Animal> listAnimals Instead, my colleagues are recommending something like: List<? extends Animal> listAnimals Why should I use wildcards instead of simple generics? Let's say I need to have a get/set method, should I use the former or the later? How are they so different?

    Read the article

  • How to use multiple restrictions in C# Generics properly?

    - by plouh
    I am attempting to bind c# generics to a class and an interface like this: public class WizardPage<T> where T : UserControl, IWizardControl { private T page; public WizardPage( T page ) { this.page = page; } } And use it with this: public MyControl : UserControl, IWizardControl { //... } Somehow C# doesn't seem to be able to decide that MyControl is a proper instance of T as public class Wizard<T> where T : UserControl, IWizardControl { private WizardPage<T> Page1; public Wizard( MyControl control ) { this.Page1 = new WizardPage(control); } } fails with error The best overloaded method match for 'Controls.WizardPage.WizardPage(T)' has some invalid arguments Am I doing something wrong or is this just not going to work?

    Read the article

  • Why doesn't C# do "simple" type inference on generics?

    - by Ken Birman
    Just curious: sure, we all know that the general case of type inference for generics is undecidable. And so C# won't do any kind of subtyping at all: if Foo<T> is a generic, Foo<int> isn't a subtype of Foo<T>, or Foo<Object> or of anything else you might cook up. And sure, we all hack around this with ugly interface or abstract class definitions. But... if you can't beat the general problem, why not just limit the solution to cases that are easy. For example, in my list above, it is OBVIOUS that Foo<int> is a subtype of Foo<T> and it would be trivial to check. Same for checking against Foo<Object>. So is there some other deep horror that would creep forth from the abyss if they were to just say, aw shucks, we'll do what we can? Or is this just some sort of religious purity on the part of the language guys at Microsoft?

    Read the article

  • Can you explain this generics behavior and if I have a workaround?

    - by insta
    Sample program below: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GenericsTest { class Program { static void Main(string[] args) { IRetrievable<int, User> repo = new FakeRepository(); Console.WriteLine(repo.Retrieve(35)); } } class User { public int Id { get; set; } public string Name { get; set; } } class FakeRepository : BaseRepository<User>, ICreatable<User>, IDeletable<User>, IRetrievable<int, User> { // why do I have to implement this here, instead of letting the // TKey generics implementation in the baseclass handle it? //public User Retrieve(int input) //{ // throw new NotImplementedException(); //} } class BaseRepository<TPoco> where TPoco : class,new() { public virtual TPoco Create() { return new TPoco(); } public virtual bool Delete(TPoco item) { return true; } public virtual TPoco Retrieve<TKey>(TKey input) { return null; } } interface ICreatable<TPoco> { TPoco Create(); } interface IDeletable<TPoco> { bool Delete(TPoco item); } interface IRetrievable<TKey, TPoco> { TPoco Retrieve(TKey input); } } This sample program represents the interfaces my actual program uses, and demonstrates the problem I'm having (commented out in FakeRepository). I would like for this method call to be generically handled by the base class (which in my real example is able to handle 95% of the cases given to it), allowing for overrides in the child classes by specifying the type of TKey explicitly. It doesn't seem to matter what parameter constraints I use for the IRetrievable, I can never get the method call to fall through to the base class. Also, if anyone can see an alternate way to implement this kind of behavior and get the result I'm ultimately looking for, I would be very interested to see it. Thoughts?

    Read the article

  • What does this Java generics paradigm do and what is it called?

    - by Tom
    I'm looking at some Java classes that have the following form: public abstract class A <E extends A<E>> implements Comparable <E> { public final int compareTo( E other ) { // etc } } public class B extends A <B> { // etc } public class C extends A <C> { // etc } My usage of "Comparable" here is just to illustrate a possible use of the generic parameter "E". Does this usage of generics/inheritance have a name? What is it used for? My impression is that this allows the abstract class to provide a common implementation of a method (such as compareTo) without having to provide it in the subclasses. However, in this example, unlike an inherited method it would restrict subclasses to invoking compareTo on other instances of the same subclass, rather than any "A" subclass. Does this sound right? Anyway, just curious if any gurus out there have seen this before and know what it does. Thanks!

    Read the article

  • Generics and Constrained Polymorphism versus Subtyping

    - by Rahul G
    Hullo all. In this (Warning: PDF) presentation on Haskell Type Classes, on slide #54, there's this question: Open Question: In a language with generics and constrained polymorphism, do you need subtyping too? My questions are: How do generics and constrained polymorphism make subtyping unnecessary? If generics and constrained polymorphism make subtyping unnecessary, why does Scala have subtyping?

    Read the article

  • Type patterns in Haskell

    - by finnsson
    I'm trying to compile a simple example of generic classes / type patterns (see http://www.haskell.org/ghc/docs/latest/html/users_guide/generic-classes.html) in Haskell but it won't compile. Any ideas about what's wrong with the code would be helpful. According to the documentation there should be a module Generics with the data types Unit, :*:, and :+: but ghc (6.12.1) complaints about Not in scope: data constructor 'Unit' etc. It seems like there's a package instant-generics with the data types :*:, :+: and U but when I import that module (instead of Generics) I get the error Illegal type pattern in the generic bindings {myPrint _ = ""} The complete source code is import Generics.Instant class MyPrint a where myPrint :: a -> String myPrint {| U |} _ = "" myPrint {| a :*: b |} (x :*: y) = "" (show x) ++ ":*:" ++ (show y) myPrint {| a :+: b |} _ = "" data Foo = Foo String instance MyPrint a => MyPrint a main = myPrint $ Foo "hi" and I compile it using ghc --make Foo.hs -fglasgow-exts -XGenerics -XUndecidableInstances P.S. The module Generics export no data types, only the functions: canDoGenerics mkGenericRhs mkTyConGenericBinds validGenericInstanceType validGenericMethodType

    Read the article

  • C# 4.0: Covariance And Contravariance In Generics Made Easy

    - by Paulo Morgado
    In my last post, I went through what is variance in .NET 4.0 and C# 4.0 in a rather theoretical way. Now, I’m going to try to make it a bit more down to earth. Given: class Base { } class Derived : Base { } Such that: Trace.Assert(typeof(Base).IsClass && typeof(Derived).IsClass && typeof(Base).IsGreaterOrEqualTo(typeof(Derived))); Covariance interface ICovariantIn<out T> { } Trace.Assert(typeof(ICovariantIn<Base>).IsGreaterOrEqualTo(typeof(ICovariantIn<Derived>))); Contravariance interface ICovariantIn<out T> { } Trace.Assert(typeof(IContravariantIn<Derived>).IsGreaterOrEqualTo(typeof(IContravariantIn<Base>))); Invariance interface IInvariantIn<T> { } Trace.Assert(!typeof(IInvariantIn<Base>).IsGreaterOrEqualTo(typeof(IInvariantIn<Derived>)) && !typeof(IInvariantIn<Derived>).IsGreaterOrEqualTo(typeof(IInvariantIn<Base>))); Where: public static class TypeExtensions { public static bool IsGreaterOrEqualTo(this Type self, Type other) { return self.IsAssignableFrom(other); } }

    Read the article

  • How to declare a Generics Action in struts2.xml file ?

    - by Rasatavohary
    Hi everyone, My problems is in a Struts2 action, where I have a class : public class MyAction<T> extends ActionSupport with a private member like this : private T myData; And I would like to declare this aciton in the struts.xml file, how can i manage to do so ? Thanks for the answer. Ps : I've tried without declaration of T, but it did not work

    Read the article

  • What should i do to test EasyMock objects when using Generics ? EasyMock

    - by Arthur Ronald F D Garcia
    See code just bellow Our generic interface public interface Repository<INSTANCE_CLASS, INSTANCE_ID_CLASS> { void add(INSTANCE_CLASS instance); INSTANCE_CLASS getById(INSTANCE_ID_CLASS id); } And a single class public class Order { private Integer id; private Integer orderNumber; // getter's and setter's public void equals(Object o) { if(o == null) return false; if(!(o instanceof Order)) return false; // business key if(getOrderNumber() == null) return false; final Order other = (Order) o; if(!(getOrderNumber().equals(other.getOrderNumber()))) return false; return true; } // hashcode } And when i do the following test private Repository<Order, Integer> repository; @Before public void setUp { repository = EasyMock.createMock(Repository.class); Order order = new Order(); order.setOrderNumber(new Integer(1)); repository.add(order); EasyMock.expectLasCall().once(); EasyMock.replay(repository); } @Test public void addOrder() { Order order = new Order(); order.setOrderNumber(new Integer(1)); repository.add(order); EasyMock.verify(repository) } I get Unexpected method call add(br.com.smac.model.domain.Order@ac66b62): add(br.com.smac.model.domain.Order@ac66b62): expected: 1, actual: 0 Why does it not work as expected ??? What should i do to pass the test ???

    Read the article

  • How to make safe cast using generics in C#?

    - by TN
    I want to implement a generic method on a generic class which would allow to cast safely, see example: public class Foo<T> : IEnumerable<T> { ... public IEnumerable<R> SafeCast<R>() where T : R { return this.Select(item => (R)item); } } However, the compiler tells me that Foo<T>.SafeCast<R>() does not define parameter 'T'. I understand this message that I cannot specify a constraint on T in the method since it is not defined in the method. But how can I specify an inverse constraint?

    Read the article

  • Java generics: What is the compiler's issue here? ("no unique maximal instance")

    - by Epaga
    I have the following methods: public <T> T fromJson( Reader jsonData, Class<T> clazz ) { return fromJson( jsonData, (Type)clazz ); } public <T> T fromJson( Reader jsonData, Type clazz ) { ... } The compiler is saying about the first method: type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds T,java.lang.Object return fromJson( jsonData, (Type)clazz ); ^ What is the problem?

    Read the article

  • Generics: How to derive from one of two classes?

    - by Yaron Naveh
    I have the following c# classes: class A : Object { foo() {} } class B : Object { foo() {} } I want to write a generic method that applies to both: void bar<T>(T t) { t.foo(); } this does not compile complaining the foo() is not a member of T. I can add a constraint for T to derive from one of the classes: void bar<T>(T t) where T : A but how can I have it for both?

    Read the article

  • extension methods with generics - when does caller need to include type parameters?

    - by Greg
    Hi, Is there a rule for knowing when one has to pass the generic type parameters in the client code when calling an extension method? So for example in the Program class why can I (a) not pass type parameters for top.AddNode(node), but where as later for the (b) top.AddRelationship line I have to pass them? class Program { static void Main(string[] args) { // Create Graph var top = new TopologyImp<string>(); // Add Node var node = new StringNode(); node.Name = "asdf"; var node2 = new StringNode(); node2.Name = "test child"; top.AddNode(node); top.AddNode(node2); top.AddRelationship<string, RelationshipsImp>(node,node2); // *** HERE *** } } public static class TopologyExtns { public static void AddNode<T>(this ITopology<T> topIf, INode<T> node) { topIf.Nodes.Add(node.Key, node); } public static INode<T> FindNode<T>(this ITopology<T> topIf, T searchKey) { return topIf.Nodes[searchKey]; } public static void AddRelationship<T,R>(this ITopology<T> topIf, INode<T> parentNode, INode<T> childNode) where R : IRelationship<T>, new() { var rel = new R(); rel.Child = childNode; rel.Parent = parentNode; } } public class TopologyImp<T> : ITopology<T> { public Dictionary<T, INode<T>> Nodes { get; set; } public TopologyImp() { Nodes = new Dictionary<T, INode<T>>(); } }

    Read the article

  • What is the problem with this Java code dealing with Generics?

    - by devoured elysium
    interface Addable<E> { public E add(E x); public E sub(E y); public E zero(); } class SumSet<E extends Addable> implements Set<E> { private E element; public SumSet(E element) { this.element = element; } public E getSum() { return element.add(element.zero()); } } It seems that element.add() doesn't return an E extends Addable but rather an Object. Why is that? Has it anything to do with Java not knowing at run-time what the object types really are, so it just assumes them to be Objects(thus requiring a cast)? Thanks

    Read the article

  • Ways to improve Java Generics and dont say get rid of wildcards and reification.

    - by mP
    Sometimes i like to write up template classes and use type parameters to make the abstract methods more type safe. Template<X> { abstract void doStuff( X ); // NOT public } While type safety is great etc, the problem remains that even though X is not visible to outside code, one must still include the type to avoid warnings. My solution in this case would be to make it possible to define a scope for type parameters (now they are always public). Would other original features besides the obvious would you like.

    Read the article

  • Error in my OO Generics design. How do I workaround it?

    - by John
    I get "E2511 Type parameter 'T' must be a class type" on the third class. type TSomeClass=class end; ParentParentClass<T>=class end; ParentClass<T: class> = class(ParentParentClass<T>) end; ChildClass<T: TSomeClass> = class(ParentClass<T>) end; I'm trying to write a lite Generic Array wrapper for any data type(ParentParentClass) ,but because I'm unable to free type idenitifiers( if T is TObject then Tobject(T).Free) , I created the second class, which is useful for class types, so I can free the objects. The third class is where I use my wrapper, but the compiler throws that error. How do I make it compile?

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >