Results 1 to 3 of 3
  1. #1
    bimtownboy is offline Member
    Join Date
    May 2013
    Rep Power

    Default Question on Generics

    I am looking at this bit of code

    public static <K,V> String toString(Map<K,V> map)
    if (map == null) return "";
    if (map.isEmpty()) return "{}";

    StringBuilder result = new StringBuilder();
    for(Map.Entry<K,V> entry : map.entrySet())
    result.append(String.format(", %s -> %s ", entry.getKey().toString(), entry.getValue().toString()));
    return "{" + result.substring(1) + "}";

    I know that the Map<K,V> is a paramterized map. I am not sure what public static <K,V> in the method signature stands for.Is it the return type ?

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Northern Virginia, United States
    Rep Power

    Default Re: Question on Generics

    The return type is of type String. The static keyword just means the method can be invoked without requiring an instance of the class. It also implies that the statements in the method will not operate on instance variables directly, only locals and the parameter list (and other static variables, if present). The K,V are the Key/Value types of the map.

    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Voorschoten, the Netherlands
    Blog Entries
    Rep Power

    Default Re: Question on Generics

    The <K, V> part in the method signature defines the method to be generic, otherwise the type Map<K, V> for the parameter type wouldn't make any sense (K and V aren't defined classes/interfaces most likely). Now the method accepts Map<String, Integer>, Map<Integer, JLabel> etc. as valid parameter types. It's a funny notation ...

    kind regards,

    Build a wall around Donald Trump; I'll pay for it.

Similar Threads

  1. Quick question about generics
    By shaboinkin in forum Advanced Java
    Replies: 3
    Last Post: 03-28-2011, 01:59 AM
  2. Generics Question
    By erversteeg in forum New To Java
    Replies: 3
    Last Post: 02-11-2011, 05:13 AM
  3. Question regarding generics
    By Leaflord in forum Advanced Java
    Replies: 9
    Last Post: 08-29-2009, 02:24 PM
  4. Generics Question
    By jdgallag in forum New To Java
    Replies: 8
    Last Post: 10-28-2008, 06:15 PM
  5. Question about java generics
    By Arrowx7 in forum New To Java
    Replies: 1
    Last Post: 08-14-2008, 02:37 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts