error while using Collection class

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • stmfc
    New Member
    • May 2007
    • 65

    error while using Collection class

    what is wrong with the code below:

    Code:
    import java.util.*;
    public class Class1 {
    	
    	public static void main(String[] args) {
    		
    		Collection c;
    		c.add("aaa");
    		c.add("bbb");
    		c.add("ccc");
    
    	}
    
    }

    i got this error:

    java.lang.Error : Unresolved compilation problems:
    The local variable c may not have been initialized
    The local variable c may not have been initialized
    The local variable c may not have been initialized
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    Guess what: the compiler is going to tell you that you didn't initialize a local
    variable. Have a look whether or not you have initialized local variable 'c'.

    kind regards,

    Jos

    Comment

    • stmfc
      New Member
      • May 2007
      • 65

      #3
      using add method i think i am initializing the local variable c,
      i am new to java, in C++ vector classes are initialized in this way.
      if this is not true in java, tell me how can i initialize c,and add values to store in variable c

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by stmfc
        using add method i think i am initializing the local variable c,
        i am new to java, in C++ vector classes are initialized in this way.
        if this is not true in java, tell me how can i initialize c,and add values to store in variable c
        Think of those Java object variables as pointers (or 'references' as they are called
        in Java) to the actual objects. The pointer/reference 'c' doesn't point to an actual
        object yet, i.e. it isn't initialized. You have to do something like this:

        [code=java]
        Collection c= new ArrayList<Strin g>();
        [/code]

        Now 'c' points to an ArrayList that can store strings (similar to vector<string> in
        C++). Also in C++ it isn't true that an 'add' method initializes the container.

        kind regards,

        Jos

        Comment

        Working...