Search Results

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

Page 10/41 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • Type-safe, generic, empty Collections with static generics

    - by Droo
    I return empty collections vs. null whenever possible. I switch between two methods for doing so using java.util.Collections: return Collections.EMPTY_LIST; return Collections.emptyList(); where emptyList() is supposed to be type-safe. But I recently discovered: return Collections.<ComplexObject> emptyList(); return Collections.<ComplexObject> singletonList(new ComplexObject()); etc. I see this method in Eclipse Package Explorer: <clinit> () : void but I don't see how this is done in the source code (1.5). How is this magic tomfoolerie happening!!

    Read the article

  • Compile Error Using MutableClassToInstanceMap with Generics

    - by user298251
    I am getting the following compile error "The method putInstance(Class, T) in the type MutableClassToInstanceMap is not applicable for the arguments (Class, Number)" on the putInstance method call. Does anyone know what I am doing wrong?? Thanks! public class TestMutableClassToInstanceMap { public final MutableClassToInstanceMap<Number> identifiers = MutableClassToInstanceMap.create(); public static void main(String[] args) { ArrayList<Number> numbers = new ArrayList<Number>(); numbers.add(new Integer(5)); TestMutableClassToInstanceMap test = new TestMutableClassToInstanceMap(numbers); } public TestMutableClassToInstanceMap(Collection<Number> numbers){ for (Number number : numbers) { this.identifiers.putInstance(number.getClass(), number); //error here } this.identifiers.putInstance(Double.class, 5.0); // This works } }

    Read the article

  • How to create a fully lazy singleton for generics

    - by Brendan Vogt
    I have the following code implementation of my generic singleton provider: public sealed class Singleton<T> where T : class, new() { Singleton() { } public static T Instance { get { return SingletonCreator.instance; } } class SingletonCreator { static SingletonCreator() { } internal static readonly T instance = new T(); } } This sample was taken from 2 articles and I merged the code to get me what I wanted: http://www.yoda.arachsys.com/csharp/singleton.html and http://www.codeproject.com/Articles/11111/Generic-Singleton-Provider. This is how I tried to use the code above: public class MyClass { public static IMyInterface Initialize() { if (Singleton<IMyInterface>.Instance == null // Error 1 { Singleton<IMyInterface>.Instance = CreateEngineInstance(); // Error 2 Singleton<IMyInterface>.Instance.Initialize(); } return Singleton<IMyInterface>.Instance; } } And the interface: public interface IMyInterface { } The error at Error 1 is: 'MyProject.IMyInterace' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'MyProject.Singleton<T>' The error at Error 2 is: Property or indexer 'MyProject.Singleton<MyProject.IMyInterface>.Instance' cannot be assigned to -- it is read only How can I fix this so that it is in line with the 2 articles mentioned above? Any other ideas or suggestions are appreciated.

    Read the article

  • C# unusual inheritance syntax w/ generics

    - by anon
    I happened upon this in an NHibernate class definition: public class SQLiteConfiguration : PersistenceConfiguration<SQLiteConfiguration> So this class inherits from a base class that is parameterized by... the derived class?   My head just exploded. Can someone explain what this means and how this pattern is useful? (This is NOT an NHibernate-specific question, by the way.)

    Read the article

  • Generics in custom configuration sections

    - by Jonn
    I tried making a custom configuration class that went on like this: WatcherServiceInfoSection<TWatcherServiceDetailElement> where TWatcherServiceDetailElement is a ConfigurationElement inside it. Now when I call the type in the ConfigSections area of AppConfig I get the error: An error occurred creating the configuration section handler for WatcherServiceInfo: Could not load type 'Library.Common.Utilities.ConfigurationHandler.WatcherServiceInfoSection<ASNDPService.Configuration.WatcherServiceDetailElement>' from assembly Is what I'm doing possible? Can I have generic types in the type attribute for a custom section element? EDIT Additionally, how about ConfigurationElementCollection objects? Like in the above example, how could I do a [ConfigurationProperty("WatcherServiceDetails", IsRequired = true, IsDefaultCollection = true)] [ConfigurationCollection(typeof(TWatcherServiceDetailElement), AddItemName = "WatcherServiceDetail")] public WatcherServiceDetailCollection<TWatcherServiceDetailElement> WatcherServiceDetails I'm aware that type parameters aren't allowed for attributes and that's what I want to know how to do.

    Read the article

  • Generics List Interface...newb question

    - by newToProgramming
    The List interface is the following: public interface List<E>{ public boolean add(Object e); public boolean remove(Object e); public boolean contains(Object e); ...etc Why aren't the add, remove and contains methods written like the following? public boolean add(E e) public boolean remove(E e) public boolean contains(E e)

    Read the article

  • Help with use of .NET Generics/Dictionary in replacing my Arrays

    - by Rollo R
    Hello, I have these code: Mypage.cs string[] strParameterName = new string[2] {"?FirstName", "?LastName"}; string[] strParameterValue = new string[2] {"Josef", "Stalin"}; MyConnection.MySqlLink(strConnection, strCommand, strParameterName, strParameterValue, dtTable); Myclass.cs public static void MySqlLink(string strConnection, string strCommand, string[] strParameterName, string[] strParameterValue, DataTable dtTable) { dtTable.Clear(); MySqlConnection MyConnection = new MySqlConnection(strConnection); MySqlCommand MyCommand = new MySqlCommand(strCommand, MyConnection); for (int i = 0; i < strParameterName.Length; i++) { MyCommand.Parameters.AddWithValue(strParameterName[i].ToString(), strParameterValue[i].ToString()); } MySqlDataAdapter MyDataAdapter = new MySqlDataAdapter(MyCommand); MyDataAdapter.Fill(dtTable); } And then my Sql Command will be something like "SELECT * FROM MyTable WHERE FirstName=?FirstName AND LastName=?LastName" As you can see, I am using arrays for the Parameter Name and Parameter Value and they both have to "match" with each other and ofcourse the Sql Command. Someone recommended to me that I use .NET "Dictionary" instead of arrays. Now I have never used that before. Can someone show me a relative example of how I am to use .NET Dictionary here?

    Read the article

  • Structuremap Configuration with generics

    - by DarthVader
    I have IRepository interface with which i want to use NHibernateRepository. How do i configure it with structure map? protected void ConfigureDependencies() { ObjectFactory.Initialize( x => { x.For<ILogger>().Use<Logger>(); x.For<IRepository<T>>().Use<NHibernateRepository<T>>(); } ); } I m getting an error on T. Another question I have is if it s OK to make an ApplicationContext static class, configure it with structure map and provide instances with it? I have read that static classes are bad, but I dont want to initialize the ApplicationContext class that I have the injections everywhere. What s the best practice for this? Thanks.

    Read the article

  • Difference between methods with and without generics

    - by isakavis
    Can someone help me understand advantages and disadvantages (if any) between the following methods which do the same function of storing away the entity to azure (in my case)? public bool Save<T>(string tableName, T entity) where T : TableEntityBase, new() { throw new NotImplementedException(); } vs public bool Save(string tableName, TableEntityBase entity) { throw new NotImplementedException(); }

    Read the article

  • Java: Why is this Subclass valid?

    - by incrediman
    Here, I have an abstract class: abstract class A<E extends A> { abstract void foo(E x); } Here's a class that extends A: class B extends A<B>{ void foo(B x){} } And here's another (E is B here on purpose): class C extends A<B>{ void foo(B x){} } Both of those classes are valid, and the reasoning for that makes sense to me. However what confuses me is how this could possibly be valid: class D extends A{ void foo(A x){} } Since when are generics optional like that? I thought the extending class (subclass) of A would be required to specify an E?

    Read the article

  • What do I return if the return type of a method is Void? (Not void!)

    - by DR
    Due to the use of Generics in Java I ended up in having to implement a function having Void as return type: public Void doSomething() { //... } and the compiler demands that I return something. For now I'm just returning null, but I'm wondering if that is good coding practice... I've also tried Void.class, void, Void.TYPE, new Void(), no return at all, but all that doesn't work at all. (For more or less obvious reasons) (See this answer for details) So what am I supposed to return if the return type of a function is Void? What's the general use of the Void class? EDIT: Just to spare you the downvotes: I'm asking about V?oid, not v?oid. The class Void, not the reserved keyword void.

    Read the article

  • How Can I List a TDictionary in Alphabetical Order by Key in Delphi 2009?

    - by lkessler
    How can I use a TEnumerator to go through my TDictionary in sorted order by key? I've got something like this: var Dic: TDictionary<string, string>; begin Dic := TDictionary<string, string>.create; Dic.Add('Tired', 'I have been working on this too long'); Dic.Add('Early', 'It is too early in the morning to be working on this'); Dic.Add('HelpMe', 'I need some help'); Dic.Add('Dumb', 'Yes I know this example is dumb'); { The following is what I don't know how to do } for each string1 (ordered by string1) in Dic do some processing with the current Dic element Dic.Free; end; So I would like to process my dictionary in the order: Dumb, Early, HelpMe, Tired. Unfortunately the Delphi help is very minimal in describing how TEnumerator works and gives no examples that I can find. There is also very little written on the web about using Enumerators with Generics in Delphi.

    Read the article

  • REG GENERIC METHOD

    - by googler1
    Hi buddies, I had a thought on using the generic method in c# as like we do in c++. Normally a method looks like this: public static (void/int/string) methodname((datatype) partameter) { return ...; } I had a thought whether can we implement the generics to this method like this: public static <T> methodname(<T> partameter) { return ...; } Using as a generic to define the datatype. Can anyone pls suggest whether the above declaration is correct and can be used in c#? Thanks in advance.

    Read the article

  • Why does Java's TreeSet not specify that its type parameter must extend Comparable?

    - by Tarski
    e.g. The code below throws a ClassCastException when the second Object is added to the TreeSet. Couldn't TreeSet have been written so that the type parameter can only be a Comparable type? i.e. TreeSet would not compile because Object is not Comparable. That way generics actually do their job - of being typesafe. import java.util.TreeSet; public class TreeSetTest { public static void main(String [] args) { TreeSet<Object> t = new TreeSet<Object>(); t.add(new Object()); t.add(new Object()); } }

    Read the article

  • how can I implement Comparable more than once?

    - by codeman73
    I'm upgrading some code to Java 5 and am clearly not understanding something with Generics. I have other classes which implement Comparable once, which I've been able to implement. But now I've got a class which, due to inheritance, ends up trying to implement Comparable for 2 types. Here's my situation: I've got the following classes/interfaces: interface Foo extends Comparable<Foo> interface Bar extends Comparable<Bar> abstract class BarDescription implements Bar class FooBar extends BarDescription implements Foo With this, I get the error 'interface Comparable cannot be implemented more than once with different arguments...' Why can't I have a compareTo(Foo foo) implemented in FooBar, and also a compareTo(Bar) implemented in BarDescription? Isn't this simply method overloading?

    Read the article

  • Activator.CreateInstance(string) and Activator.CreateInstance<T>() difference

    - by Juan Manuel Formoso
    No, this is not a question about generics. I have a Factory pattern with several classes with internal constructors (I don't want them being instantiated if not through the factory). My problem is that CreateInstance fails with a "No parameterless constructor defined for this object" error unless I pass "true" on the non-public parameter. Example // Fails Activator.CreateInstance(type); // Works Activator.CreateInstance(type, true); I wanted to make the factory generic to make it a little simpler, like this: public class GenericFactory<T> where T : MyAbstractType { public static T GetInstance() { return Activator.CreateInstance<T>(); } } However, I was unable to find how to pass that "true" parameter for it to accept non-public constructors (internal). Did I miss something or it isn't possible?

    Read the article

  • Scala: "Parameter type in structural refinement may not refer to an abstract type defined outside th

    - by raichoo
    Hi, I'm having a problem with scala generics. While the first function I defined here seems to be perfectly ok, the compiler complains about the second definition with: error: Parameter type in structural refinement may not refer to an abstract type defined outside that refinement def >>[B](a: C[B])(implicit m: Monad[C]): C[B] = { ^ What am I doing wrong here? trait Lifter[C[_]] { implicit def liftToMonad[A](c: C[A]) = new { def >>=[B](f: A => C[B])(implicit m: Monad[C]): C[B] = { m >>= (c, f) } def >>[B](a: C[B])(implicit m: Monad[C]): C[B] = { m >> a } } } IMPORTANT: This is NOT a question about Monads, it's a question about scala polymorphism in general. Regards, raichoo

    Read the article

  • C# Reflection - How can I tell if object o is of type KeyValuePair and then cast it?

    - by Logan
    Hi All I'm currently trying to write a Dump() method from LinqPad equivalent iin C# for my own amusment. I'm moving from Java to C# and this is an exercise rather than a business requirement. I've got almost everything working except for Dumping a Dictionary. The problem is that KeyValuePair is a Value type. For most other Value types I simply call the ToString method but this is insufficient as the KeyValuePair may contain Enumerables and other objects with undesirable ToString methods. So I need to work out if it's a KeyValuePair and then cast it. In Java I could use wildcard generics for this but I don't know the equivalent in C#. Your quest, given an object o, determine if it's a KeyValuePair and call Print on its key and value. Print(object o) { ... } Thanks!

    Read the article

  • Java Interface Reflection Alternatives

    - by Phaedrus
    I am developing an application that makes use of the Java Interface as more than a Java interface, i.e., During runtime, the user should be able to list the available methods within the interface class, which may be anything: private Class<? extends BaseInterface> interfaceClass. At runtime, I would like to enum the available methods, and then based on what the user chooses, invoke some method. My question is: Does the Java "Interface" architecture provide any method for me to peek and invoke methods without using the Reflection API? I wish there were something like this (Maybe there is): private Interface<? extends BaseInterface> interfaceAPI; public void someMethod(){ interfaceAPI.listMethods(); interfaceAPI.getAnnotations(); } Maybe there is some way to use Type Generics to accomplish what I want? Thanks, Phaedrus

    Read the article

  • [Java6] Same source code, Eclipse build success but Maven (javac) fails

    - by EnToutCas
    Keep getting this error when compiling using Maven: type parameters of <X>X cannot be determined; no unique maximal instance exists for type variable X with upper bounds int,java.lang.Object Generics type interference cannot be applied to primitive types. But I thought since Java5, boxing/unboxing mechanism works seamlessly between primitive types and wrapper classes. In any case, the strange thing is Eclipse doesn't report any errors and happily compiles. I'm using JDK1.6.0_12. What could possibly be the problem here?

    Read the article

  • Covariant return types in Java enums

    - by Kelvin Chung
    As mentioned in another question on this site, something like this is not legal: public enum MyEnum { FOO { public Integer doSomething() { return (Integer) super.doSomething(); } }, BAR { public String doSomething() { return (String) super.doSomething(); } }; public Object doSomething(); } This is due to covariant return types apparently not working on enum constants (again breaking the illusion that enum constants are singleton subclasses of the enum type...) So, how about we add a bit of generics: is this legal? public enum MyEnum2 { FOO { public Class<Integer> doSomething() { return Integer.class; } }, BAR { public Class<String> doSomething() { return String.class; } }; public Class<?> doSomething(); } Here, all three return Class objects, yet the individual constants are "more specific" than the enum type as a whole...

    Read the article

  • what's a good way to implement something that looks like Dictionary<string, string, Dictionary<strin

    - by jcollum
    I've got a data structure that is Key, Value, OtherValues(key, Value). So the OtherValues are attached to the first Key and aren't always there. I can do this as Dictionary<Key, ValueAndListOfOptionalValues> where ValueAndListOfOptionalValues is a class with a string and a Dictionary<string, string>. I'm wondering if that's really the best way to do it? Sometimes I think that I'm missing some important classes in the Generics namespace, maybe there are better classes out there that I'm not aware of.

    Read the article

  • Using generic type from other generic parameter

    - by DEHAAS
    Hi, I have a question about .net generics. Consider the following code: public class Test<TKey> { TKey Key { get; set; } } public class Wrapper<TValue, TKey> where TValue : Test<TKey> { public TValue Value { get; set; } } Now, when using this code, I could do something like this: Wrapper<Test<int>, int> wrapper = new Wrapper<Test<int>, int>(); The int type parameter has to be provided twice. Is it possible to modify the Wrapper definition, to require TValue to be a generic type, and use this 'nested' generic type parameter insted of the TKey type parameter?

    Read the article

  • Passing a generic class to a java function?

    - by rodo
    Is it possible to use Generics when passing a class to a java function? I was hoping to do something like this: public static class DoStuff { public <T extends Class<List>> void doStuffToList(T className) { System.out.println(className); } public void test() { doStuffToList(List.class); // compiles doStuffToList(ArrayList.class); // compiler error (undesired behaviour) doStuffToList(Integer.class); // compiler error (desired behaviour) } } Ideally the List.class and ArrayList.class lines would work fine, but the Integer.class line would cause a compile error. I could use Class as my type instead of T extends Class<List> but then I won't catch the Integer.class case above.

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >