lambas aufrufen



  • Hey,

    ich hatte hier gelesen wie man lambdas aufruft
    http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html

    darin heisst es, dass man irgend eine instanzmethode auf einem object typen aufrufen kann:

    "Reference to an Instance Method of an Arbitrary Object of a Particular Type"

    Nun habe ich das mal probiert und bei mir klappt zwar das angegebene Beispiel aber mein eigenes klappt nicht:

    public class LambdaTest {
        public static void main(String[] args) {
            Game[] games = new Game[]{
                    new Game("Game3", 7),
                    new Game("Game1", 10),
                    new Game("Game4", 4),
                    new Game("Game2", 6),
            };
    
            printGames(games);
            Arrays.sort(games, Game::sortStatic);
            Arrays.sort(games, Game::sortInstance);  // java: no suitable method found for sort(org.tcial.Game[],Game::sortInstance); method java.util.Arrays.<T>sort(T[],java.util.Comparator<? super T>) is not applicable (cannot infer type-variable(s) T(argument mismatch; invalid method reference cannot find symbol   method sortInstance(T,T)...
            Arrays.sort(games, games[0]::sortInstance);
            Arrays.sort(games, games[0]::sortStatic);  // static bound method reference
            printGames(games);
    
            String[] stringArray = { "Barbara", "James", "Mary", "John",
                    "Patricia", "Robert", "Michael", "Linda" };
            Arrays.sort(stringArray, String::compareToIgnoreCase);  // why does this work?
        }
    
        private static void printGames(Game[] games) {
            for (Game game : games) {
                System.out.println(game.name + " " + game.age);
            }
        }
    }
    
    class Game {
        public String name;
        public int age;
    
        public Game(String name, int age) {
            this.name = name;
            this.age = age;
        }
    
        public int sortInstance(Game g1, Game g2) {
            return sortStatic(g1, g2);
        }
    
        public static int sortStatic(Game g1, Game g2) {
            return g1.age - g2.age;
        }
    }
    

    Jemand eine Idee warum?



  • lamm schrieb:

    Jemand eine Idee warum?

    Weil sortInstance nur einen Parameter haben darf.


Anmelden zum Antworten