0

I have this array:

String[] countriesList = {
                "Japan",
                "Sverige",
                "Tyskland",
                "Spanien",
                "Syrien",
                "Litauen",                                      
};

I want to be able to add another thing to the array, in this case this [6]th position. Is it possible to do this by JOPtionPane? This is what I've done this far, however nothing happens nor does any errors occur.

String addland = JOptionPane.showInputDialog("Vilket land vill du lägga till?").trim();
            countriesList[6] = addland;             
2
  • 2
    Try to use an ArrayList. Commented Sep 10, 2015 at 11:23
  • 2
    Arrays have fixed size. Use resizeable collection like List, or create array with bigger size. Commented Sep 10, 2015 at 11:24

1 Answer 1

1

Arrays start their counting from 0, so you could use countriesList[5] = addland;

You may use a dynamic list to perform your task. They are better in every situation and should be superior to simple Arrays

Try to use this

List<String> countriesList = new ArrayList<>(
Arrays.asList("Japan", "Sverige", "Tyskland", "Spanien", "Syrien", "Litauen"));

String addland = JOptionPane.showInputDialog("Vilket land vill du lägga till?").trim();
countriesList.set(5,addland);
System.out.println(countriesList);

Output, after entering asdadsad:

[Japan, Sverige, Tyskland, Spanien, Syrien, asdadsad]

To add a land to the existing list use countriesList.add(addland); instead of countriesList.set(5,addland);

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

4 Comments

I get The type List is not generic; it cannot be parameterized with arguments <String> ArrayList cannot be resolved to a type
Maybe you importet the wrong List. Make sure your imports are java.util.ArrayList , java.util.Arrays and java.util.List, also dont use 6 as a set variable because array counting starts at 0 so 5 is your last entry
So I still can't add another String to the List? That was my question all along. I want to create [6].
You can add as much items as you want to the array list (in fact only 2,147,483,647 items because thats the limit of int). Thats the good part about it. Just use the add method on an array list object. Use this documentation to learn more about Array Lists. My comment was on the set method which requires an existing element to replace -> set(5,yourstring) means that the String on position 5 gets replaced with the second argument.

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.