0

Is it possible to store a whole array as a node in a linked list. I am using the Linked List collection java provides and I keep getting an error for the following code.

List<Object[]> params = new LinkedList<Object[]>(); 
params.add(new Object[] { "ahhsjhs", {"jsdjdsk","djksdjsdk"}, true}); 

Type mismatch: cannot convert from String[] to Object

5
  • 3
    Do you mean params.add(new Object[]{"ahhsjhs", new String[]{"jsdjdsk", "djksdjsdk"}, true}); but are you sure you want this structure of data, I would suggest to use classes to store this type of data! Commented Jun 5, 2020 at 20:36
  • No I would like this structure of data. And yes that is what i mean Commented Jun 5, 2020 at 20:38
  • 1
    It would help if we knew what error you get... Commented Jun 5, 2020 at 20:52
  • The corrected code by @YCF_L just works, try this: public static void main(String[] args) { List<Object[]> params = new LinkedList<Object[]>(); params.add(new Object[] { "ahhsjhs", new String[]{"jsdjdsk","djksdjsdk"}, true}); System.out.println(params); } Commented Jun 5, 2020 at 20:54
  • You did not declared this: "{"jsdjdsk","djksdjsdk"}" right as you didn't specify what is this so the compiler can't understand what object to put there, i would assume you want this as: "new String[]{"jsdjdsk","djksdjsdk"}" Commented Jun 5, 2020 at 21:07

3 Answers 3

1

You can use this and not get error

List<Object[]> params = new LinkedList<Object[]>(); 
params.add(new Object[]{"ahhsjhs", new String[]{"jsdjdsk", "djksdjsdk"}, true});

You can even do this and there is nothing wrong

List<Object[]> params = new LinkedList<Object[]>(); 
params.add(new Object[]{"ahhsjhs", new Object[]{new Object[] {"@@", new Object[] {"@@"},"@@"}, "@@"}, true});

But it is bad practice! You should approach to OOP.

Sign up to request clarification or add additional context in comments.

Comments

0

It is possible, and you're doing it (almost) correctly. Compiler get confused with the inline declaration, doing the declaration outside should get you past the error, something like the following:

        List<Object[]> params = new LinkedList<Object[]>();
        String[] a = new String[]{"jsdjdsk","djksdjsdk"};
        params.add(new Object[] { a });
        params.add(new Object[] { "ahhsjhs", true});
        System.out.println(params);
    }

This with java:8.

Comments

0

Just put this String[] objects:

List<Object[]> params = new LinkedList<Object[]>();
String[] objects = new String[] { "jsdjdsk", "djksdjsdk" };
params.add(new Object[] { "ahhsjhs", objects, true });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.