简体   繁体   中英

Java untyped generic classes, removing their functions generics types

Ok Question about javas generics, iterable, and for-each loop. The problem being that, if I declare my 'Test' class untyped, I lose all generic information on all my functions and for-each is not likeing that at all.

Example

public class Test<T> implements Iterable<Integer>{

    public Test() {}

    public Iterator<Integer> iterator() {return null;}

    public static void main(String[] args) {
        Test t = new Test();

        //Good,
        //its returning an Iterator<object> but it automatically changes to  Iterator<Integer>
        Iterator<Integer> it = t.iterator();

        //Bad
        //incompatable types, required Integer, found Object
        for(Integer i : t){
        }
    }Untyped generic classes losing 
}

When 'Test t' is untyped, the 'iterator()' function returns 'iterator' instead of a 'iterator < Integer >'.

I'm not exactly sure for the reason behind it, I know a fix for that is just use a wild card on 'Test < ? > t = new test()'. However this is a less than ideal solution.
Is their any way to only edit the class declaration and its functions and have the for each loop work untyped?

You should just do the following:

public class Test implements Iterable<Integer>{

Remove the generic type all together.

Your Test class is not generic at all. It is simply implementing a generic interface. Declaring a generic type is not necessary. This will also have the benefit of remove that generic warning you were getting.

@Eugene makes a good point. If you actually wanted a generic Test type, you should declare Test as a generic iterator:

You should just do the following:

public class Test implements Iterable<Integer>{

Remove the generic type all together.

Your Test class is not generic at all. It is simply implementing a generic interface. Declaring a generic type is not necessary. This will also have the benefit of remove that generic warning you were getting.

public class Test<T> implements Iterable<T>{

And then, make sure you make Test generic when you instantiate it.

Test<Integer> t = new Test<Integer>;

Then calls to for(Integer i: t) will compile.

You should either write this:

public class Test implements Iterable<Integer>{
  ...

or actually generify your class:

public class Test<T> implements Iterable<T> {

    public Iterator<T> iterator() {return null;}

    public static void main(String[] args) {
        Test<Integer> t = new Test<Integer>();

        Iterator<Integer> it = t.iterator();

        for(Integer i : t){
        }
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM