Java: Problems using lambda expressions in generic Listing method

Asked

Viewed 79 times

1

The problem would be that I cannot multiply the variables that return from Listing using lambda (e*e), it keeps asking to create a Listing method using Object, but using Generics. I appreciate any contribution.

public Element<T> listing() {
            Element<T> e = head;
            System.out.println("");
            System.out.println("Start listing... ");
            while (e != null) {
                System.out.println("Value: " + e.getValue());
                e = e.getNext();
            }
            System.out.println("End listing");
            System.out.println("");
            return e;

        }

Calling for

Deque<String> deque = new Deque<String>(); 
deque.addFirst("zero");
deque.addFirst("first");
deque.addFirst("secound");
deque.addFirst("third");
deque.addLast("fifth");

deque.listing((e)-> System.out.println(e*e));
  • 1

    I didn’t tell you what the problem is.

  • The method listing presented does not receive argument, but the use of it in Deque<T> gets a Consumer<T>. What problem are you really facing?

  • @Piovezan: The problem would be that I cannot multiply the variables that return from Listing using lambda (e*e), it keeps asking to create a Listing method using Object, but using Generics. I appreciate any contribution

  • The class Deque it was you who defined it? With that method listing?

  • @Jeffersonquesado Yes, she who defined, in another question here on the site.

  • Related: https://answall.com/q/308221/64969

  • 1

    The problem of wanting to print e*e is that this does not work with Generics. In this case strings are being used, but Java does not "first" * "third", for example. I think you need to explain better what you want to do there we try to find a solution.

  • 2

    In Java the multiplication operator only works with primitive types (integer or floating point numbers), and I believe also with classes Wrappers as Integer or Double (thanks to autoboxing).

  • ah I understood the mess. So if I switched to Deque<Integer> deque = new Deque<Integer>(); and added instead of string deque.addFirst(1); deque.addFirst(2); deque.addFirst(3); deque.addFirst(4); deque.addLast(5); would have no trouble using.Listing((e)->

  • The method listing does not yet receive a parameter, such as a Consumer<T>

  • Thank you! It worked.

Show 6 more comments

1 answer

-2


Browser other questions tagged

You are not signed in. Login or sign up in order to post.