w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Generic interface implementing multiple generic types - how to share a method implementation?
Yes, given that Dog and Cat both inherit from a common base class or implement a common interface like e.g. IAnimal. Then for instance: private IEnumerable<T> ApplyFilter(IEnumerable<T> list) where T:IAnimal { // do the work here } In other words, if Cat and Dog share the filtering logic, it surely refers to a common base.

Categories : C#

implementing a generic method with varargs
I wrote two test files. Here's the first: public class Test { public static void main(String... args) { System.out.println(java.util.Arrays.toString(args)); } } And here's the second: public class Test { public static void main(String[] args) { System.out.println(java.util.Arrays.toString(args)); } } (The only difference between these two files is the String[] args vs String... args.) Then, I ran javap -c on each file to see the disassembly. The contents of the main method were identical: Code: 0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream; 3: aload_0 4: invokestatic #3 // Method java/util/Arrays.toString:([Ljava/lang/Object;)Ljava/lang/String; 7: invokevirtual #4

Categories : Java

Implementing a generic method from interface?
You cannot create an array of a generic type parameter. You cannot declare a method with a type parameter as its argument which will match an existing method's signature after erasure. This is happening because you are implementing a raw type. So, you should declare your class like this - public class BoundedQueueArray<T> implements BoundedQueue<T> and remove the following array creation code from the constructor - elements = new T[capacity]; It will be better if you can use a List (interface, implementation) in place of the array (see Effective Java, Item 25), and stay away from raw types as much as possible (see Effective Java, Item 23). Example - private List<T> elements; // convert array to list and - elements = new ArrayList<T>(); // cre

Categories : Java

implementing comprable method in a generic way in Java for sorting
The following works for me. All I did was remove the <E> in the class declaration and changed <E> to <E extends Comparable<E>> in selectionSort. The generic <E> in the class declaration is unnecessary and potentially confusing since your class doesn't actually need to be generic. Only the methods in the class are generic, not the class itself. Second, the selectionSort method requires the element type passed in to be comparable to itself. You can represent this by E extends Comparable<E>. import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SelectionSortGenerics { private <E> void swap(E[] a, int i, int j) { if (i != j) { E temp = a[i]; a[i] = a[j]; a[j] = tem

Categories : Java

How to Force 3rd party implementing/inheriting class to run a generic method in java?
If you make your runProcess method final, then subclasses won't be able to override your method, and this can ensure that writeToLog is called. You can make writeToLog private to not expose the implementation. You can make doYourProcessSpecificThing protected so that it can't be called directly, but subclasses can still define their own implementation. This is called the Template Method Pattern. This allows the implementer (you) to define what specific behavior can be overridden, yet retaining control over the overall process/algorithm.

Categories : Java

Type mismatch found when implementing traits with parameter in the return
In your class MyMockOfBase Boolean is the name of type parameter, just like T: class MyMockOfBase extends SomeBaseTrait{ def someFun[T](args:SomeArgs)(f: => T):T= true } You are trying to use true as T. I guess you want to do something like this: trait SomeBaseTrait[B]{ def someFun(args:SomeArgs)(f: => B):B } class MyMockOfBase extends SomeBaseTrait[Boolean]{ def someFun(args:SomeArgs)(f: => Boolean):Boolean = true }

Categories : Scala

Modifying value type in generic class implementing generic interface C#
You are trying to add 10 (an integer) to a value of type T. T can be an integer, or a DateTime, or a List, or some other custom class. This means that there is absolutely no guarantee that your T will be able to add itself to an integer. Unfortunately, there is no way in C# to add a generic type constraint that will restrict the parameter to a type that will support a certain operation. There are workaround, but they are ugly. i.e. you could have: class Point<T>{ ... } and then have class IntPoint : Point<int>, IDoable<int> { ... } class DoublePoint : Point<double>, IDoable<Double> { ... }

Categories : C#

Autofac: generic class implementing a non generic interface not being injected
So I think I figured it out. It boils down to a chicken or egg scenario. When you register a generic class via the RegisterGeneric method, Autofac will not automatically register the closed types unless it detects them somewhere in your object graph as a dependency. Ctor 1 doesn't trigger closed generics to be registered: public MessageHandlerFactory(IEnumerable<IMessageHandler> handlers){ } Ctor 2 does trigger closed generics to be registered: public MessageHandlerFactory(IEnumerable<IMessageHandler> handlers, MessageHandler<ComplexMessage> complexHandler, MessageHandler<SimpleMessage> simpleHandler ){} Once I manually registered the closed generics using the code below, Autofac b

Categories : C#

Using nested type declared in a generic class within the generic interface that the class is implementing
The only way that you can make this work is to define the procedural type outside of the implementing class. Like this: type IMyIntf<A> = interface; TMyProc<A> = reference to procedure(Intf: IMyIntf<A>); IMyIntf<A> = interface procedure Foo(Proc: TMyProc<A>); end; TMyClass<A> = class(TInterfacedObject, IMyIntf<A>) procedure Foo(Proc: TMyProc<A>); end;

Categories : Delphi

return generic IEnumerable when passing concrete type parameter for a generic method
You cannot convert the Type class to a generic T parameter without using reflection. The parameter also needs to be present as part of the method. Jon Skeet was using type inference by example combined with generics in order to guarantee type safety and simplify the generic code. Unfortunately you will lose that type safety using Type and reflection. private IEnumerable<EntityObject> GetFilteredData(Type entityType, SortedList<string, string> filterList, List<int> weeks) { var method = typeof(<class>).GetMethod("GetFilteredDataImpl"); var generic = method.MakeGenericMethod(entityType); return (IEnumerable<EntityObject>)generic.Invoke(this, new[] {

Categories : C#

Getting a generic type of implementing class
Well you could write implements Cloneable, but then you'd be using the raw type, which is generally a bad idea. For the sake of stronger typing, you're better off sticking with what you've got.

Categories : Java

Java: Implementing generic Iterator
You can add a generic parameter like this: public class IteratorWrapper<T> implements Enumeration<T> { Iterator<T> iterator; public IteratorWrapper(Iterator<T> iterator){ this.iterator = iterator; } public boolean hasMoreElements(){ return iterator.hasNext(); } public T nextElement(){ return iterator.next(); } } Then, your initialization will look like this: IteratorWrapper<String> iteratorWrapper = new IteratorWrapper<String>(arrayList.iterator());

Categories : Java

Reflection - Navigate a non-generic method from a generic type definition to a concrete one
You can use the MakeGenericType method, like this: m.DeclaringType.MakeGenericType(typeof(int)) and then probably GetMethod again if you really want to go this way: m.DeclaringType.MakeGenericType(typeof(int)).GetMethod("Method"); However, consider Jon Skeet's comment for simpler solution.

Categories : C#

Late-Binding Exception Calling Generic Method of Generic Type in C#
Your GetFirstGenericArgument() is wrong. Calling GetGenericTypeDefinition() returns the underlying open generic type. Its type argument is T. Instead, you should write t.GetGenericArguments()[0], which will get the value of the generic type parameter for the closed type. No; your code doesn't make any sense. What on earth are you trying to do? I suspect that you actually want to write public class CollectionHandler<T> { public void Handle(IEnumerable<T> collection) { // Look ma, no reflection! } }

Categories : C#

Storing object implementing a generic interface in a collection
You need to use either a non generic root interface: public interface IWidget<T> : IWidget { } or specify the type at the point of declaration: List<IWidget<MyType>> widgetList;

Categories : C#

Proper way a implementing property based on generic type
The problem is your Repository property declaration - you just need to specify the type argument, which you can do directly given that you've only got one type which will work, by the looks of it: public IRepository<WhsePricingRatesAddOn> Repository { get; set; } I don't understand why you say you want TypeRate to be unaware of the type of T, as it's clearly set in the constructor... You could make TypeRate generic too (i.e. make it TypeRate<T> and declare your property as IRepository<T>), but then the constructor body wouldn't compile, as it's explicitly casting to IRepository<WhsePricingRatesAddOn>. It's possible that you could introduce a non-generic IRepository interface as a super-interface of IRepository<T> - but you've already got IEntity, and all

Categories : C#

Implementing multiple iterators in generic class - c# - IEnumerable(T)
It's possible, but it will be messy to use. You have to implement both the IEnumerable<DLLItem<T>> and IEnumerable<T> interfaces: public class DLL<T> : IEnumerable<DLLItem<T>>, IEnumerable<T> The GetNumerator methods will collide, so you would have to resort to explicit interface implemenation, which forces the caller to cast the object to the right interface type before accessing the enumerator: var dllItems = ((IEnumerable<DLLItem<T>>)someDll); var Ts = ((IEnumerable<T>)someDll); My recommendation is to not go that way. Instead expose properties for one or both of the enumerators. Look for example at the Dictionary<TKey, TValue> class. It implements IEnumerator<KeyValuePair<TKey, TValue>> and exposes a

Categories : C#

Generic type conversion in generic method
You seem to hope that the class called NetworkEventBase<T> would be covariant in T. But generic classes can't be covariant in C# (generic interfaces can). See other threads on this issue.

Categories : C#

How does adding an unused generic parameter to an interface stop a class implementing it?
Your class is trying to implement the raw type IGiveUp - that raw type doesn't know anything about generics, so the method signature after type erasure is then just: void surrender(List l) It doesn't matter that the method parameter didn't use a type parameter from the interface declaration: type erasure removes all traces of generics from signatures. Basically, you should avoid raw types as far as possible. For more details, follow the links above to sections of the JLS, or read the Java Generics FAQ.

Categories : Java

Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type?
Why undefined generic parameter of variable drops explicit generic parameter of it's method's return type? A is a raw type. That's a type with all generics dropped in the API dropped, even ones with fixed type arguments. See the JLS section 4.8 and the Raw Types section of the Java Generics FAQ for more information. In this case, if you want any A, you can use a wildcard: public static void test(A<?> i)

Categories : Java

C++: Non generic method in generic class?
You can use static_assert to prevent compilation if the method in question is used with the wrong type: #include <type_traits> // for std::is_same template <typename T> struct Foo { void foo() const {} void bar() const { static_assert(std::is_same<T, int>::value, "T is not int"); } }; int main() { Foo<double> fd; fd.foo(); // OK //fd.bar(); // ERROR: bar() only works with Foo<int> Foo<int> fi; fi.foo(); // OK fi.bar(); // OK } Alternatively, you can use SFINAE to control the types for which the method in question exists. template <typename T> class Foo { public: void foo() const {} template<typename T2 = T, typename = typename std::enable_if<std::is_same<T, int>::valu

Categories : C++

How to Write a generic method to find the maximal element and invoke that method?
Would it make any difference if Comparable<? super T> is replaced with Comparable<T> ? if so How ? Remember that Comparables are always consumers, i.e., a Comparable<T> consumes T instances, so it should always be preferrable to use Comparable<? super T> instead of Comparable<T> (Quoting - PECS). It would make difference in case you are comparing a type whose super class implements a Comparable<SuperType>. Consider the following code: class Parent implements Comparable<Parent> { protected String name; @Override public int compareTo(Parent o) { return this.name.compareTo(o.name); } } class Child extends Parent { public Child(String name) { this.name = name; } } Now if you give your type parameter as

Categories : Java

How to pass the result of calling a statically imported generic method to another method?
There is no syntax in Java to specify the type arguments of a method at the call site without qualifying the method call with its containing class or instance. Note that this has nothing to do with static imports. For example, look at this code: <T> void x(T x) {} void y() { this.<Object>x(""); } No static methods involved at all, but the issue is the same: in this case you cannot avoid the explicit this.

Categories : Java

Generic method doesn't compile - the method is not applicable for the arguments
You cannot insert anything into a List defined as List<? extends Foo>. This is discussed in a decent level of detail in the JDK documentation (see the bottom of the page).

Categories : Java

Can't pass the result of a generic method to another method?
In both the first and the third example, you stated that you are talking about a List<String>, yet on the second one you said f(init(5)), which could be a List<Integer>. I'm not 100% that's the only reason, but check it out :)

Categories : Java

Method for convert generic list to another generic list
You can do it using LINQ, but you still need to provide a function that should be used to convert elements: public static List<TResult> ListCopy<TSource, TResult>(List<TSource> input, Func<TSource, TResult> convertFunction) { return input.Select(x => convertFunction(x)).ToList(); } And sample usage (with simple casting as conversion function) var t = ListConvert(l, x => (Two)x);

Categories : C#

Implementing multiple interfaces having same method
Not as far as syntax is concerned but if the intent of one of the methods is not adhered to, its contract is broken and the code can be considered as broken. Using your analogy, if I promised Michael to wear a blue shirt instead of a red shirt, and I can't wear two shirts, then I will have to break at least one promise. The same can hold for the methods: if keeping one contract would mean breaking the other then it's in fact a bad idea to implement both interfaces. Edit:Contract broken, As per Class C signature It should implement two methods,but ultimately its implementing only one method and omitting another. Reference

Categories : Java

implementing a method in objective-c with Xcode
The method syntax is correct. You surely have some syntax error before in the same file. Provided that you are writing this code inside a implementation (.m) file (otherwise that's the issue), check that every other method in the .m file has a correct syntax. Also if you are also declaring the method in the interface file (.h) check it's syntax there. It should have the same signature of the implementation. Bottom line here's how your code should look like: Whatever.h @interface Whatever : NSObject //... other stuff - (IBAction)changeGreeting:(id)sender; //... other stuff @end Whatever.m @implementation //... other stuff - (IBAction)changeGreeting:(id)sender { self.userName = self.textField.text; NSString *nameString = self.userName; if ([nameString length] ==

Categories : Objective C

Implementing shouldSelectViewController method in UiTabBarViewController
First of all , get the UITabbarController's object from the application's view controller flow. Then make a tabbarcontroller's property in appDelegate and assign it's value like, if([viewController isKindOfClass:[UITabBarController class]]){ UITabBarController *objTabbarController = (UITabBarController *) viewController; self.objTabbarController = objTabbarController; self.objTabbarController.delegate = self; } assign the delegate to it , @interface AppDelegate : UIResponder <UIApplicationDelegate,UITabBarDelegate> And implement the method in AppDelegate.m file In shouldSelectViewController just return YES; And In - (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewContr

Categories : IOS

Infinite recursion when implementing power method in R
I finally got it working: A = matrix(c(1, 1, 2, 0), 2, 2, byrow=TRUE) x0 = rnorm(2) thresh = 1e-22 powerm = function(A, x0, thresh) { m0 = x0[which.max(abs(x0))] x1 = A %*% (x0 / m0) m1 = x1[which.max(abs(x1))] cat(m1, ' ') if(abs(m1 - m0) < thresh) { return(m1) } else { powerm(A, x1, thresh) } } ev1 = powerm(A, x0, thresh) A1 = A - diag(2)*ev1 ev2 = ev1 + powerm(A1, x0, thresh) It looks like python has a problem with deep recursion, so I changed the code a bit: import numpy as np A = np.matrix([[1, 1], [2, 0]]) x0 = np.matrix([1, 0]).reshape(2, 1) thresh = 1e-33 def powerm(A, x0, thresh): m0 = x0.flat[abs(x0).argmax()] x1 = A * (x0 / m0) m1 = x1.flat[abs(x1).argmax()] while abs(m1 - m0) > thresh:

Categories : R

Implementing custom "cover?"-based method
class Range def cover_e? rng rng.minmax.all?{|i| self.include? i} end end p (1..10).cover_e?((2..5)) p (5..15).cover_e?((10..20)) # >> true # >> false Or class Range def cover_e? rng (rng.to_a | self.to_a).size == self.size end end p (1..10).cover_e?((2..5)) p (5..15).cover_e?((10..20)) # >> true # >> false

Categories : Ruby

trouble implementing method from inherited class -ios
declare doesItMatch method in MatchTest.h file like in MatchTest.h -(NSString*)doesItMatch:(UIButton *)sender; compiler is not able to file doesItMatch method's declaration in .h file that's why that error is there.

Categories : IOS

Implementing the add method for a Binary Search Tree
Inside the addItem method, thisRoot is just a local variable (bound to the second argument of the method). Resetting it doesn't change anything except inside the method. You have to assign the new BinaryNode<Type>(item) that you construct to either the left or right pointer of an existing node. (If I'm being vague, that's because I don't want to give the answer away.)

Categories : Java

Implementing abstract 'overlaps' method for different shapes?
What you need is a "how big is other" type function. If we make it real simple, and just use a bounding box (a rectangle that is big enough to cover the entire shape), then we could do something like this: (For simplicy, I'm using rect as a term for a rectangle) class Shape { ... virtual rect BoundingBox() = 0; bool overlaps(const Shape& other) { return BoundingBox.FitsInside(other.BoundingBox()); } }; Obviously, you'll then have to write the function of fitsinside for two rectangles and BoundingBox for each shape, but it shouldn't be too hard. To make a "is this Star completely covered by this Oval?" makes for a slightly more challenging solution [you will need to have a complete outline of both shapes, and an Oval outline may be quite a lot of points to be precisel

Categories : C++

Provide type-class when implementing/override method
No, and this shouldn't work at all. Given your defnition of Processor, this code will compile: val processor: Processor[Int] = foo() // foo() is some function that returns a Processor processor.process[Object](x => new Object()) Now if foo is actually implemented as def foo() = new Plant[Int]() then its process method won't work with B = Object.

Categories : Scala

Using recursion to populate arrays, without implementing method overloading?
Very commonly, a recursive solution requires two methods. The top method is called with the externally meaningful arguments, does any required set-up, and calls the recursive method. The recursive method takes additional arguments. For example, a recursive binary search may have a top method that that takes as parameters only the probe and a reference to the array. The recursive method also takes a start and end index, so that it can limit itself to a slice of the array. Java programs usually have a lot of small methods, and Java implementations are designed to handle that. If you can make your code be clear and work with two methods, go with two methods and move on to the next thing.

Categories : Java

What is the current method of implementing an options menu in an application?
It really depends on the particular app, existing UX, branding and a ton of other design considerations. In general, starting from scratch, a good starting point (though not universally!) would be the action bar. It gives the user access to ways of manipulating the data on screen, as well as a way of consistently presenting secondary functionality (the overflow menu). Design docs, implementation docs. I would heartily recommend going through the Patterns section of the design documentation, as it explains the rationale behind many of the core design decisions. P.S. The reason I'm eager to underline that it's not universal is apps with established UX and user expectations. Examples include Facebook, Path, Google Maps. They all have their reasons for not sticking strictly to the action ba

Categories : Android

Generic Type x Generic Parameter: Building a "very generic" structure
Well, first of all, you're overcomplicating this. All you really need to do is: public void add(final Tree<? extends T> subTree) { Theres no need to parameterize add(). But anyways, I'll address your original attempt: You want SubTree extends Tree<Leaf>, because even if Leaf extends T you can't guarantee that SubTree extends Tree<T> with SubTree<Leaf> matches. E.g. if your class hierarchy is: public class Base { } public class A extends Base { } public class B extends Base { } If Leaf is A and SubTree is Tree<B> then add (final SubTree<Leaf>) does not match Tree<B>. So conceptually you actually want this: public <Leaf extends T, SubTree extends Tree<Leaf>> void add(final SubTree<Leaf> subTree) { Of course that is not va

Categories : Java

Why I cant call method from other class when implementing custom authentication provider
From your description it seems that method simpleService.doNothing() never returns, thus causing your thread to get stuck, that is why the other code in your authenticate() method isn't reached. And by the way, a simple test with the debugger should reveal the problem easily. Edit: Since I understand debugging is not an option here, the way to go is to print to log before calling the method, inside the method and after the method. Since you've done it and the method doesn't print, there are now 2 options: simpleReceiver is null, a simple try catch with logs should reveal it. simpleReceiver is not of type SimpleReceiver but a derived class that does infinite long work in its function, if that is the case a simple log print of the instance type should reveal it.

Categories : Java

Java class implementing a method with a parameter that is of the subtype specified in the interface
Firstly, syntax. The declaration: public interface Buffable<V> { public void buff(Buff<V extends Buff> buff); } Should be: public interface Buffable<V extends Buff> { public void buff(Buff<V> buff); } The type variable you want, should be specified in the class declaration. But you say: I also want to define classes that implement the buff method using an input parameter that is of a subtype of Buff. This way, the below declaration would suit your statement better: public interface Buffable<V extends Buff<?>> { public void buff(V buff); } You may want to change that <?> part if you need a more specific type of Buff. Lastly, other required change and the final classes: public abstract class Buff<V> { public V

Categories : Java



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.