Search Results

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

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

  • Java generics - getting the type..

    - by peter
    Hi! I'm a c# guy giving Java a try .. so how would I do the following in java. in C# public T create_an_instance_of<T>(){ T instance = default (T); // here's usually some factory to create the implementation instance = some_factory.build<T>(); // or even.. instance = some_factory.build(typeOf(T) ); return instance; }

    Read the article

  • Generics in a bidirectional association

    - by Verhoevenv
    Let's say I have two classes A and B, with B a subtype of A. This is only part of a richer type hierarchy, obviously, but I don't think that's relevant. Assume A is the root of the hierarchy. There is a collection class C that keeps track of a list of A's. However, I want to make C generic, so that it is possible to make an instance that only keeps B's and won't accept A's. class A(val c: C[A]) { c.addEntry(this) } class B(c: C[A]) extends A(c) class C[T <: A]{ val entries = new ArrayBuffer[T]() def addEntry(e: T) { entries += e } } object Generic { def main(args : Array[String]) { val c = new C[B]() new B(c) } } The code above obviously give the error 'type mismatch: found C[B], required C[A]' on the new B(c) line. I'm not sure how this can be fixed. It's not possible to make C covariant in T (like C[+T <: A]) because the ArrayBuffer is non-variantly typed in T. It's not possible to make the constructor of B require a C[B] because C can't be covariant. Am I barking up the wrong tree here? I'm a complete Scala newbie, so any ideas and tips might be helpful. Thank you! EDIT: Basically, what I'd like to have is that the compiler accepts both val c = new C[B]() new B(c) and val c = new C[A]() new B(c) but would reject val c = new C[B]() new A(c) It's probably possible to relax the typing of the ArrayBuffer in C to be A instead of T, and thus in the addEntry method as well, if that helps.

    Read the article

  • Question marks in Java generics.

    - by gnucom
    I tried to make sure this wasn't a duplicate post, sorry if I was blind. This is a small snippet of code taken from some of the examples that accompany the Stanford Parser. I've been developing in Java for about 4 years, but have never had a very strong understanding of what this style of code is supposed to indicate. List<? extends HasWord> wordList = toke.tokenize(); I'm not worried about the details of the code. What I'm confusing about is what exactly the generic expression is supposed to convey, in English. Can someone explain this to me? Thanks!

    Read the article

  • Inferring type from method generics

    - by ng
    I am from a Java background and I am looking from the equivalent in c# for the following. public interface Reader { <T> T read(Class<? extends T> type); } Such that I can do the following, constraining the parameter and inferring the return type. Cat cat = reader.read(Cat.class); Dog dog = reader.read(Dog.class); I was hoping something like this would work in c# but I am not sure it will. public interface Reader { T Read<T>(); } And and do this. public class TypeReader : Reader { public T Read<T>() { Type type = T.GetType(); ... } } Is something like this even possible in c#?

    Read the article

  • c# How to implement a collection of generics

    - by Amy
    I have a worker class that does stuff with a collection of objects. I need each of those objects to have two properties, one has an unknown type and one has to be a number. I wanted to use an interface so that I could have multiple item classes that allowed for other properties but were forced to have the PropA and PropB that the worker class requires. This is the code I have so far, which seemed to be OK until I tried to use it. A list of MyItem is not allowed to be passed as a list of IItem even though MyItem implements IItem. This is where I got confused. Also, if possible, it would be great if when instantiating the worker class I don't need to pass in the T, instead it would know what T is based on the type of PropA. Can someone help get me sorted out? Thanks! public interface IItem<T> { T PropA { get; set; } decimal PropB { get; set; } } public class MyItem : IItem<string> { public string PropA { get; set; } public decimal PropB { get; set; } } public class WorkerClass<T> { private List<T> _list; public WorkerClass(IEnumerable<IItem<T>> items) { doStuff(items); } public T ReturnAnItem() { return _list[0]; } private void doStuff(IEnumerable<IItem<T>> items) { foreach (IItem<T> item in items) { _list.Add(item.PropA); } } } public void usage() { IEnumerable<MyItem> list= GetItems(); var worker = new WorkerClass<string>(list);//Not Allowed }

    Read the article

  • A generic list of generics

    - by SnOrfus
    I'm trying to store a list of generic objects in a generic list, but I'm having difficulty declaring it. My object looks like: public class Field<T> { public string Name { get; set; } public string Description { get; set; } public T Value { get; set; } /* ... */ } I'd like to create a list of these. My problem is that each object in the list can have a separate type, so that the populated list could contain something like this: { Field<DateTime>, Field<int>, Field<double>, Field<DateTime> } So how do I declare that? List<Field<?>> (I'd like to stay as typesafe as possible, so I don't want to use an ArrayList).

    Read the article

  • C# Generic Generics (A Serious Question)

    - by tahirhassan
    In C# I am trying to write code where I would be creating a Func delegate which is in itself generic. For example the following (non-Generic) delegate is returning an arbitrary string: Func<string> getString = () => "Hello!"; I on the other hand want to create a generic which acts similarly to generic methods. For example if I want a generic Func to return default(T) for a type T. I would imagine that I write code as follows: Func<T><T> getDefaultObject = <T>() => default(T); Then I would use it as getDefaultObject<string>() which would return null and if I were to write getDefaultObject<int>() would return 0. This question is not merely an academic excercise. I have found numerous places where I could have used this but I cannot get the syntax right. Is this possible? Are there any libraries which provide this sort of functionality?

    Read the article

  • Java generics: actual class as a generic parameter.

    - by user554916
    What do I write instead of "TheClass" to make this work? Or is there an alternative way to do it (possibly without making WithName and WithAge generic)? class Item { NeigborList<TheClass> neighbors; } class WithName extends Item { // here I want neighbors to be a NeighborList<WithName> String name; void someMethod() { System.out.println(neighbors.nearestTo(this).name); } } class WithAge extends Item { // here I want neighbors to be a NeighborList<WithAge> int age; void someOtherMethod() { System.out.println(neighbors.nearestTo(this).age); } }

    Read the article

  • C# overloading with generics: bug or feature?

    - by TN
    Let's have a following simplified example: void Foo<T>(IEnumerable<T> collection, params T[] items) { // ... } void Foo<C, T>(C collection, T item) where C : ICollection<T> { // ... } void Main() { Foo((IEnumerable<int>)new[] { 1 }, 2); } Compiler says: The type 'System.Collections.Generic.IEnumerable' cannot be used as type parameter 'C' in the generic type or method 'UserQuery.Foo(C, T)'. There is no implicit reference conversion from 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.ICollection'. If I change Main to: void Main() { Foo<int>((IEnumerable<int>)new[] { 1 }, 2); } It will work ok. Why compiler does not choose the right overload?

    Read the article

  • Generics Java and Shadowing of type parameters

    - by rubixibuc
    This code seems to work fine class Rule<T> { public <T>Rule(T t) { } public <T> void Foo(T t) { } } Does the method type parameter shadow the class type parameter? Also when you create an object does it use the type parameter of the class? example Rule<String> r = new Rule<String>(); Does this normally apply to the type parameter of the class, in the situation where they do not conflict? I mean when only the class has a type parameter, not the constructor, or does this look for a type parameter in the constructor? If they do conflict how does this change? SEE DISCUSSION BELOW if I have a function call x = <Type Parameter>method(); // this is a syntax error even inside the function or class ; I must place a this before it, why is this, and does everything still hold true. Why don't I need to prefix anything for the constructor call. Shouldn't Oracle fix this.

    Read the article

  • Problem with generics

    - by jess
    I have this code in base class protected virtual bool HasAnyStuff<TObject>(TObject obj) where TObject:class { return false; } In child class I am overriding protected override bool HasAnyStuff<Customer>(Customer obj) { //some stuff if Customer.sth etc return false; } I am getting this error '''Type parameter declaration must be an identifier not a type''' What is it I am doing wrong here?

    Read the article

  • Java using generics with lists and interfaces

    - by MirroredFate
    Ok, so here is my problem: I have a list containing interfaces - List<Interface> a - and a list of interfaces that extend that interface: List<SubInterface> b. I want to set a = b. I do not wish to use addAll() or anything that will cost more memory as what I am doing is already very cost-intensive. I literally need to be able to say a = b. I have tried List<? extends Interface> a, but then I cannot add Interfaces to the list a, only the SubInterfaces. Any suggestions? EDIT I want to be able to do something like this: List<SubRecord> records = new ArrayList<SubRecord>(); //add things to records recordKeeper.myList = records; The class RecordKeeper is the one that contains the list of Interfaces (NOT subInterfaces) public class RecordKeeper{ public List<Record> myList; }

    Read the article

  • Generics not so generic !!

    - by Aymen
    Hi I tried to implement a generic binary search algorithm in scala. Here it is : type Ord ={ def <(x:Any):Boolean def >(x:Any):Boolean } def binSearch[T <: Ord ](x:T,start:Int,end:Int,t:Array[T]):Boolean = { if (start > end) return false val pos = (start + end ) / 2 if(t(pos)==x) true else if (t(pos) < x) binSearch(x,pos+1,end,t) else binSearch(x,start,pos-1,t) } everything is OK until I tried to actually use it (xD) : binSearch(3,0,4,Array(1,2,5,6)) the compiler is pretending that Int not a member of Ord, well what shall I do to solve this ? Thanks

    Read the article

  • Subterranean IL: Generics and array covariance

    - by Simon Cooper
    Arrays in .NET are curious beasts. They are the only built-in collection types in the CLR, and SZ-arrays (single dimension, zero-indexed) have their own commands and IL syntax. One of their stranger properties is they have a kind of built-in covariance long before generic variance was added in .NET 4. However, this causes a subtle but important problem with generics. First of all, we need to briefly recap on array covariance. SZ-array covariance To demonstrate, I'll tweak the classes I introduced in my previous posts: public class IncrementableClass { public int Value; public virtual void Increment(int incrementBy) { Value += incrementBy; } } public class IncrementableClassx2 : IncrementableClass { public override void Increment(int incrementBy) { base.Increment(incrementBy); base.Increment(incrementBy); } } In the CLR, SZ-arrays of reference types are implicitly convertible to arrays of the element's supertypes, all the way up to object (note that this does not apply to value types). That is, an instance of IncrementableClassx2[] can be used wherever a IncrementableClass[] or object[] is required. When an SZ-array could be used in this fashion, a run-time type check is performed when you try to insert an object into the array to make sure you're not trying to insert an instance of IncrementableClass into an IncrementableClassx2[]. This check means that the following code will compile fine but will fail at run-time: IncrementableClass[] array = new IncrementableClassx2[1]; array[0] = new IncrementableClass(); // throws ArrayTypeMismatchException These checks are enforced by the various stelem* and ldelem* il instructions in such a way as to ensure you can't insert a IncrementableClass into a IncrementableClassx2[]. For the rest of this post, however, I'm going to concentrate on the ldelema instruction. ldelema This instruction pops the array index (int32) and array reference (O) off the stack, and pushes a pointer (&) to the corresponding array element. However, unlike the ldelem instruction, the instruction's type argument must match the run-time array type exactly. This is because, once you've got a managed pointer, you can use that pointer to both load and store values in that array element using the ldind* and stind* (load/store indirect) instructions. As the same pointer can be used for both input and output to the array, the type argument to ldelema must be invariant. At the time, this was a perfectly reasonable restriction, and maintained array type-safety within managed code. However, along came generics, and with it the constrained callvirt instruction. So, what happens when we combine array covariance and constrained callvirt? .method public static void CallIncrementArrayValue() { // IncrementableClassx2[] arr = new IncrementableClassx2[1] ldc.i4.1 newarr IncrementableClassx2 // arr[0] = new IncrementableClassx2(); dup newobj instance void IncrementableClassx2::.ctor() ldc.i4.0 stelem.ref // IncrementArrayValue<IncrementableClass>(arr, 0) // here, we're treating an IncrementableClassx2[] as IncrementableClass[] dup ldc.i4.0 call void IncrementArrayValue<class IncrementableClass>(!!0[],int32) // ... ret } .method public static void IncrementArrayValue<(IncrementableClass) T>( !!T[] arr, int32 index) { // arr[index].Increment(1) ldarg.0 ldarg.1 ldelema !!T ldc.i4.1 constrained. !!T callvirt instance void IIncrementable::Increment(int32) ret } And the result: Unhandled Exception: System.ArrayTypeMismatchException: Attempted to access an element as a type incompatible with the array. at IncrementArrayValue[T](T[] arr, Int32 index) at CallIncrementArrayValue() Hmm. We're instantiating the generic method as IncrementArrayValue<IncrementableClass>, but passing in an IncrementableClassx2[], hence the ldelema instruction is failing as it's expecting an IncrementableClass[]. On features and feature conflicts What we've got here is a conflict between existing behaviour (ldelema ensuring type safety on covariant arrays) and new behaviour (managed pointers to object references used for every constrained callvirt on generic type instances). And, although this is an edge case, there is no general workaround. The generic method could be hidden behind several layers of assemblies, wrappers and interfaces that make it a requirement to use array covariance when calling the generic method. Furthermore, this will only fail at runtime, whereas compile-time safety is what generics were designed for! The solution is the readonly. prefix instruction. This modifies the ldelema instruction to ignore the exact type check for arrays of reference types, and so it lets us take the address of array elements using a covariant type to the actual run-time type of the array: .method public static void IncrementArrayValue<(IncrementableClass) T>( !!T[] arr, int32 index) { // arr[index].Increment(1) ldarg.0 ldarg.1 readonly. ldelema !!T ldc.i4.1 constrained. !!T callvirt instance void IIncrementable::Increment(int32) ret } But what about type safety? In return for ignoring the type check, the resulting controlled mutability pointer can only be used in the following situations: As the object parameter to ldfld, ldflda, stfld, call and constrained callvirt instructions As the pointer parameter to ldobj or ldind* As the source parameter to cpobj In other words, the only operations allowed are those that read from the pointer; stind* and similar that alter the pointer itself are banned. This ensures that the array element we're pointing to won't be changed to anything untoward, and so type safety within the array is maintained. This is a typical example of the maxim that whenever you add a feature to a program, you have to consider how that feature interacts with every single one of the existing features. Although an edge case, the readonly. prefix instruction ensures that generics and array covariance work together and that compile-time type safety is maintained. Tune in next time for a look at the .ctor generic type constraint, and what it means.

    Read the article

  • Generic collection as a Java method argument

    - by Guido
    Is there any way to make this work in Java? public static void change(List<? extends Object> list, int position1, int position2) { Object obj = list.get(position1); list.set(position1, list.get(position2)); list.set(position2, obj); } The only way I've successfully avoided warnings and errors is this: public static <T> T change(List<T> list, int position1, int position2) { T obj = list.get(position1); list.set(position1, list.get(position2)); list.set(position2, obj); return obj; } but I don't like to be forced to return a value.

    Read the article

  • Open generic interface types of open implementation don't equal interface type?

    - by George Mauer
    Here's a test that should, in my opinion be passing but is not. [TestMethod] public void can_get_open_generic_interface_off_of_implementor() { typeof(OpenGenericWithOpenService<>).GetInterfaces().First() .ShouldEqual(typeof(IGenericService<>)); } public interface IGenericService<T> { } public class OpenGenericWithOpenService<T> : IGenericService<T> { } Why does this not pass? Given Type t = typeof(OpenGenericWithOpenService<>) how do I get typeof(IGenericService<)? I'm generally curious, but if you're wondering what I'm doing, I'm writing a Structuremap convention that forwards all interfaces implemented by a class to the implementation (as a singleton).

    Read the article

  • Escaping Generics with T4 Templates

    - by Gavin Stevens
    I've been doing some work with T4 templates lately and ran into an issue which I couldn't find an answer to anywhere.  I finally figured it out, so I thought I'd share the solution. I was trying to generate a code class with a T4 template which used generics The end result a method like: public IEnumerator GetEnumerator()             {                 return new TableEnumerator<Table>(_page);             } the related section of the T4 template looks like this:  public IEnumerator GetEnumerator()             {                 return new TableEnumerator<#=renderClass.Name#>(_page);             } But this of course is missing the Generic Syntax for < > which T4 complains about because < > are reserved. using syntax like <#<#><#=renderClass.Name#><#=<#> won't work becasue the TextTransformation engine chokes on them.  resulting in : Error 2 The number of opening brackets ('<#') does not match the number of closing brackets ('#>')  even trying to escape the characters won't work: <#\<#><#=renderClass.Name#><#\<#> this results in: Error 4 A Statement cannot appear after the first class feature in the template. Only boilerplate, expressions and other class features are allowed after the first class feature block.  The final solution delcares a few strings to represent the literals like this: <#+    void RenderCollectionEnumerator(RenderCollection renderClass)  {     string open = "<";   string close =">"; #>    public partial class <#=renderClass.Name#> : IEnumerable         {             private readonly PageBase _page;             public <#=renderClass.Name#>(PageBase page)             {                 _page = page;             }             public IEnumerator GetEnumerator()             {                 return new TableEnumerator<#=open#><#=renderClass.Name#><#=close#>(_page);             }         } <#+  }  #> This works, and everyone is happy, resulting in an automatically generated class enumerator, complete with generics! Hopefully this will save someone some time :)

    Read the article

  • Using Unity Application Block – from basics to generics

    - by nmarun
    I just wanted to have one place where I list all the six Unity blogs I’ve written. Part 1: The very basics – Begin using Unity (code here) Part 2: Registering other types and resolving them (code here) Part 3: Lifetime Management (code here) Part 4: Constructor and Property or Setter Injection (code here) Part 5: Arrays (code here) Part 6: Generics (code here) Hope this helps someone (and this is the smallest blog I’ve posted till now).

    Read the article

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