Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Question about a warning re:Generics in Java

Options
  • 03-12-2008 9:41pm
    #1
    Closed Accounts Posts: 7,794 ✭✭✭


    I'm writing Java using Eclipse, and it's giving me a warning if I try to declare a Generic class without parameterising it. Thing is, I don't want to parameterise it until I instantiate it later on in the program, for example, say I have a generic class, "MyClass", which takes one parameter, and I want to do something like this:
    public static void main(String args[]){
    	Terminal terminal = new Terminal();
    	MyClass myclass; 		//Eclipse warns me here
    
    	
    	switch(terminal.readInt()){	//read an int from the user
    		case 1:
    			myclass = new MyClass<Integer>();
    		break;
    
    		case 2:
    			myclass = new MyClass<String>();
    		break;
    	}
    }
    

    Now this runs fine, so should I just ignore the warning or is there something I'm doing that's fundamentally wrong here?

    EDIT: Ok, I realise I can write '"MyClass<?> myclass" when declaring it, and there'll be no warnings in this code, however, this seems to mean I can't pass any non-null parameters to any methods I might call on myclass later on in my program... :S


Comments

  • Registered Users Posts: 2,082 ✭✭✭Tobias Greeshman


    I'm guessing you're using java 5 at least here.

    One thing you can do is use wildcards in your definition to allow the class have any Object paramaterised. This should shut up eclipse. The warning is no harm anyways.
    class MyClass <T> {
      // ...
    }
    
    // ...
    
      public static void main(String[] args) {
    
         MyClass <? extends Object> my;
    
         my = new MyClass<String>();
    
      }
    


  • Closed Accounts Posts: 7,794 ✭✭✭JC 2K3


    Yeah, I know I can use a wildcard, but then that stops me from passing non-null parameters to methods taking generic parameters.

    For example:
    class MyClass <T> {
      private T thing;
    
      public setThing(T thething){
        thing = thething;
      }
    }
    
    // ...
    
      public static void main(String[] args) {
    
         MyClass <? extends Object> my;
    
         my = new MyClass<String>();
    
    [COLOR="Red"]     my.setThing("This is a string");    //I get an error here[/COLOR]
    
      }
    

    I'm guessing ignoring the warning I get when I don't parameterise is the way forward....


  • Registered Users Posts: 5,618 ✭✭✭Civilian_Target


    Well... if you're not going to strongly type it, why use wildcards? Just declare it regular 1.4 style!


Advertisement