3 Replies Latest reply: Jan 20, 2014 1:37 PM by rp0428 RSS

    Java generics

    814889

      I am learning java generics I am having trouble understanding some things

       

       

      If am allowed to create

       

      List<T> list = new ArrayList<T>();

       

      then why cant do the following

       

      list.add("string");

       

       

      and why I cannot do this.

       

      List<?>  wildcard = new ArrayList<?>();

        • 1. Re: Java generics
          rp0428
          I am learning java generics I am having trouble understanding some things

           

           

          If am allowed to create

           

          List<T> list = new ArrayList<T>();

           

          Well - you can't ALWAYS use 'T' like that. You have to have previously defined 'T'. This isn't valid as standalone code:

          class NewClass {

             List<T> list = new ArrayList<T>();
          }

          But these are:

          class NewClass<abc> {

             List<abc> list = new ArrayList<abc>();
          }


          class NewClass<T> {

             List<T> list = new ArrayList<T>();
          }

          The 'abc' or 'T' is 'Type Parameter Name'

          then why cant do the following

           

          list.add("string");

          Because that 'string' is a String and that is NOT an instance of type 'T'.

          and why I cannot do this.

           

          List<?>  wildcard = new ArrayList<?>();

          Because in 'ArrayList<?>()' the '?' is the NAME of a type and question marks are NOT valid characters that can be used in object names.

           

          See the trails for Generics in The Java Tutorials.

          http://docs.oracle.com/javase/tutorial/java/generics/types.html

          Type Parameter Naming Conventions

          By convention, type parameter names are single, uppercase letters. This stands in sharp contrast to the variable naming conventions that you already know about, and with good reason: Without this convention, it would be difficult to tell the difference between a type variable and an ordinary class or interface name.

          The most commonly used type parameter names are:

          • E - Element (used extensively by the Java Collections Framework)
          • K - Key
          • N - Number
          • T - Type
          • V - Value
          • S,U,V etc. - 2nd, 3rd, 4th types

          That reference to 'variable naming' leads you to the rules for naming:

          http://docs.oracle.com/javase/tutorial/java/nutsandbolts/variables.html#naming

          Naming

          Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:

          • Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.
          • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.

          There is no mention of '?' in those naming conventions.

          • 2. Re: Java generics
            814889

            Then why in below class  if I have defined T is this class then why

             

             

                 List<T>   list = new ArrayList<T>();

                 list.add(t);

             

            is not working

             

             

            and how do I create List<T> ?

            package generic;

            import java.util.ArrayList;
            import java.util.List;

            public class WildCard<T>  {

            List<T> list;
            T t;

            public List<T> getList() {
              return list;
            }

            public void setList(List<T> list) {
              this.list = list;
            }


            public T getT() {
              return t;
            }

            public void setT(T t) {
              this.t = t;
            }

            public  void printList(List<T> list) {
                 for (Object elem : list)
                     System.out.println(elem + " ");
                 System.out.println();
            }

            public static <T> void main(String[] args) {
             
                 List<T>   list = new ArrayList<T>();
                 list.add(t);
                
                
             
            }
            }

            • 3. Re: Java generics
              rp0428

              Then why in below class  if I have defined T is this class then why

               

                   List<T>   list = new ArrayList<T>();

                   list.add(t);

               

              is not working

              Did you read the exception message that you are getting? It tells you why it 'is not working':

              non-static variable t cannot be referenced from a static context

              Main is a static method but 't' is an instance variable. This works for me:

              public static <T> void main(String[] args) {

                   T t = null;

                   List<T>   list = new ArrayList<T>();

                   list.add(t);

              If you want to learn generics you need to learn them from someone that knows them. You won't be successful just randomly trying things.

               

              You also need to use a good IDE (e.g. NetBeans) and pay attention to the exceptions and error messages that you get.

               

              Go through The Java Tutorials trails I referenced earlier. Learn those basic examples before you start trying to do your own thing.

               

              Otherwise you are in for nothing but trouble.