1

I trying to migrate from Eclipse to Android Studio. The code compiles and works in Eclipse but won't compile in Android Studio.

The code in question is converting a list from a type to a list of a subtype. It uses the method mapList which uses generics.

Android Studio is complaining that the argument to mapList to be the same as the resulting type.

Is there a problem with the code or Android Studio?

public class Fruit {
}

public class Banana extends Fruit {
}

private <D, S extends D> List<D> mapList(List<S> sourceList) {
    List<D> result = new ArrayList<D>();

    for(S sourceElement : source) {
        result.add((D) sourceElement);
    }

    return result;
}

private void bananaToFruit() {
    List<Banana> bananaList = new ArrayList<Banana>();
    List<Fruit> fruitList = mapList(bananaList);
}
Niels
  • 1,026
  • 9
  • 17
  • android studio is in its beta version ..working with it is like pain in a*** better u use eclipse – Shakeeb Ayaz Nov 19 '13 at 09:00
  • I did expect bugs and errors in Android Studio, but not compile errors in plain java code as I supposed it worked like IntelliJ in that matter. – Niels Nov 19 '13 at 09:08

2 Answers2

2

In Eclipse, you're probably using the Eclipse compiler (ecj). Android Studio uses Gradle, which uses the Java command-line compiler (javac). It's not a problem with Android Studio, but a difference between how the two compilers handle generics. I'm not sure which one is acting correctly in this case.

If you're using plain IntelliJ, you have the option of using the Eclipse compiler, but if you're using Android Studio with a Gradle-based project, you've only got javac. It might be possible to get Gradle working with ecj, but I don't think there's any simple setting for it; you'd probably have to hack Gradle itself.

A quick search reveals this question comparing javac and ecj, which has some links that may shed more light on it:

What is the difference between javac and the Eclipse compiler?

Community
  • 1
  • 1
Scott Barta
  • 79,344
  • 24
  • 180
  • 163
  • You are right, thank you. This is a problem with the javac compiler. This lead to [another SO-question](http://stackoverflow.com/questions/13533880/java-generics-compile-in-eclipse-but-not-in-javac) having the same problem. – Niels Nov 20 '13 at 13:50
0

Somehow this code works in Intellij (probably Android Studio too)

private <D, S extends D> D[] mapArray(List<S> sourceList) {
        List<D> result = new ArrayList<D>();
        result.addAll(sourceList);
        return (D[]) result.toArray();
    }

private void bananaToFruit() {
        List<Banana> list = new ArrayList<Banana>();
        Fruit[] data = mapArray(list);
        List<Fruit> fruitList = Arrays.asList(data);
    }

However, I cannot figure out why it does not work when calling mapList, but works if separate the process. Will come back later if I find out anything.

Lawrence Choy
  • 6,088
  • 1
  • 20
  • 30