views:

136

answers:

5

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?

+1  A: 
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)

Bozho
well i tried it and it didn't work. What I should have said, is that I am trying to make an interface generic. The interface is iterable.
ProxyProtocol
ah, so it's not your class, but an existing one. Well, Iterable IS generic, so what exactly 'didn't work'. Are you using Java 1.5+ ?
Bozho
+4  A: 

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.

Jorn
`T` cannot be a primitive type.
Bart Kiers
well, he referred to my answer where the primitives issues is explained.
Bozho
Ok, suppose I want the target of a for-each to be a primitive, so itsfor(int i : MyClass) something like that. Is this possible to do?
ProxyProtocol
You can't do for (int i: MyClass). MyClass would have to be an int or Integer. You could use the generic type T in a loop though.for(T var: myIterableOfTypeT).
Jeremy Raymond
I'd suggest reading a tutorial first.
Bozho
+2  A: 

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

Pascal Thivent
it's the question, rather than you, that is missing something
Bozho
+1  A: 

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.

bmargulies
A: 

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

final List< Integer> list;

...

for(final int i : list)
{
}
TofuBeer