How to Add Strings to a Java List

When groups of data needs to be stored quickly, the traditional, vanilla array is the most common choice. However, the array has a number of disadvantages, not least of which is that new data cannot be added to the array without recreating it. The List interface provides an "add" method that simplifies this process for the programmer, and even makes it more efficient in some situations.

Instructions

    • 1

      Create a basic Java class. To do this, open any text editor and type:

      public class StringList {

      public static void main(String[] args) {

      }

      }

    • 2

      Create the list. The "List" type in Java is abstract, so it cannot be directly created. Instead, you must create one of its subtypes, such as the ArrayList, LinkedList, and Set. Here, the ArrayList will be used. Type the following between the brackets of the "public static void main" method:

      ArrayList list = new ArrayList();

    • 3

      Add a string to the list using the "add" method by typing the following on the next line:

      String s = "This is a string of English text.";

      list.add(s);

Tips & Warnings

  • The different implementations of the "List" interface in Java have different performance characteristics. The ArrayList is a good compromise, but in situations where performance is paramount, another class may serve your needs better.

Related Searches:

References

Comments

Related Ads

Featured