0

I and more used to how things are done in C# than how things are done in java. The following lines are in java:

List <String> cIDs = null;
cIDs.add("something");

This shows a warning in eclipse. It says that the variable cIDs can only be null at this location. This tell me that the add will fail.

I tried writing some instantiate code:

cIDs = new List<String>()

but this does not work in java.

How do I add elements to a list of strings in java?

xarzu
  • 8,657
  • 40
  • 108
  • 160
  • 1
    `List` is the interface. If you want to instanciate it, you need to use a class that implements the interface, such as `ArrayList`. – AntonH Aug 06 '14 at 23:15

3 Answers3

2

Try this:

    import java.util.ArrayList;
    ...

    cIDs = new ArrayList<String>();

List is an interface and thus cannot be instantiated. ArrayList is a concrete class that implements that interface. Thus is can be instantiated.

EJK
  • 12,332
  • 3
  • 38
  • 55
2

List is an interface, it is abstract, not to be used to create/instantiate real object. So you have to use its "implementation" either your own:

public YourListimplements List<String>{
....
}
List<String> aList = new YourList();

( anonymously inline)

   List<String> aList= new List<String>() {
   ....
   }

or existing one :

public class java.util.ArrayList extends java.util.AbstractList implements java.util.List ....{
...
}

List<String> aList= new ArrayList();
Phung D. An
  • 2,402
  • 1
  • 22
  • 23
1

List is an interface, this means it cannot be instantiated. Instead, use the ArrayList implementation:

List<String> cIDs = new ArrayList<>();
cIDs.add("something");

If the diamond operator (<>) isn't supported, use new ArrayList<String>().

August
  • 12,410
  • 3
  • 35
  • 51