ProxyProtocol
ProxyProtocol

Reputation: 9

Making a generic parameterized type of anything

So I am trying to make a parameterized type that will work for anytype in Java this includes anything that is an object, and also the primitives types. How would i go about doing this?

Ok, suppose I want the target of a for-each to be a primitive, so its

for(int i : MyClass)

something like that. Is this possible to do?

Upvotes: 0

Views: 231

Answers (5)

user8681
user8681

Reputation:

Going from your comment on Bozho's answer, you probably want something like this:

interface MyInterface<T> extends Iterable<T> {
}

and no, you can't do that for primitive types. You could simulate an iterator for a primitive type, but it will never really be Iterable, as in, usable in a for-each loop.

Upvotes: 4

TofuBeer
TofuBeer

Reputation: 61526

This should work, but I suspect it is not what you are really after...

final List< Integer> list;

...

for(final int i : list)
{
}

Upvotes: 0

bmargulies
bmargulies

Reputation: 100023

You can't do this sort of thing, usefully, for primitive types. If you are 'lucky' you get evil autoboxing, and if you are unlucky you might get protests from the compiler. If you look at GNU Trove or Apache Commons Primitives, you'll see the parallel universe that results from the desire to do the equivalent of the collections framework on primitive types.

I suppose that if you are sure that the overhead of autoboxing is acceptable to you it might make sense, but I can't get over my tendency to find it revolting.

Upvotes: 1

Pascal Thivent
Pascal Thivent

Reputation: 570325

I may be missing something but why don't you just implement Iterable<T>?

Upvotes: 2

Bozho
Bozho

Reputation: 597076

public MyClass<E>

it doesn't include primitive types, i.e. you can't declare MyClass<int> myobj;, but you can use the wrappers (java.lang.Integer, etc)

Upvotes: 1

Related Questions