6

I have a simple function like:

private void function(LinkedList<String> a, LinkedList<String> b)

We already know that if those arguments were only string, passing values inline would be easy, like:

function("aaa", "bbb")

But is there a way to pass inline a LinkedList?

I tried with:

function(["A", "B", "C"], ["A", "B"])

but it does not work.

0

3 Answers 3

10

Change the type from LinkedList to the List interface, and then you can use Arrays.asList(T...) like

function(Arrays.asList("A", "B", "C"), Arrays.asList("A", "B"))
Sign up to request clarification or add additional context in comments.

Comments

2

There are ways to do it, but I'm not sure they will be clearer/shorter than the non-inline ways.

For example, using Stream API :

function (Stream.of("A","B","C").collect(Collectors.toCollection(LinkedList::new)),
          Stream.of("A","B").collect(Collectors.toCollection(LinkedList::new)));

You could use Array.asList if you don't need a specific List implementation (such as LinkedList) and don't mind the resulting List being fixed sized.

Or you can use Array.asList and still get a LinkedList :

function(new LinkedList<String>(Arrays.asList("A", "B", "C")), 
         new LinkedList<String>(Arrays.asList("A", "B")));

Comments

0

There is a way, without using any framework, but spoiler alert, it does not look any good to me:

function((LinkedList<String>) Arrays.asList("A", "B", "C"),
        (LinkedList<String>) Arrays.asList("A", "B"));

If you are using the LinkedList just to concatenate the strings, then you could use StringBuilder, that could do the job and looks much better:

public void doSomething() {
    function(new StringBuilder()
            .append("A")
            .append("B")
            .append("C"), 
        new StringBuilder()
            .append("A")
            .append("B"));
}

private void function(StringBuilder a, StringBuilder b) { ... }

Cheer, Nikolas

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.