Why 2 castings in return statement of entrySet() of HashMap?

Hi
When looking through the code of the HashMap class in jdk 1.5 in Eclipse 3.2 I see the following:
public Set<Map.Entry<K,V>> entrySet() {
Set<Map.Entry<K,V>> es = entrySet;
return (es != null ? es : (entrySet = (Set<Map.Entry<K,V>>) (Set) new EntrySet()));
Here I am wondering why there in the return statement are 2 (two) castings:
return (es != null ? es : (entrySet = (Set<Map.Entry<K,V>>) (Set) new EntrySet()));
, where I think of (Set<Map.Entry<K,V>>) (Set)
Can anyone give me a good explanation to this?
Thank you!

Hi,
you're right: the casts are not really necessary at all, since an assignment from a raw type is possible without an explicit cast. Either with or without the casts, the compiler will issue an "unchecked" warning.
(And, of course, a single cast to the target type would also work here.)
The "correct" way to fix the code would be to make the inner class EntrySet a parameterized class by deriving it from AbstractSet<Map.Entry<K,V>>. Then all "unchecked" warnings would automatically disappear.
My guess is that by the time the developer generified the HashMap, there where still compiler bugs preventing him from declaring inner classes such as EntrySet correctly. Since then, nobody's touched the code again.

Similar Messages

  • Return statement on a void?

    Theres a part that i dont understand, and if its possible i'd like to be helped a bit with it ^_^.
    This class is part of a program that uses threading to display a consistent "Tick Tock", but the part that i dont get is why is there a return statement on the method that is on bold, isn't void supposed to mean that it doesnt return a value, is the return statement just used to get out of the if loop?, or maybe something else! help is appreciated!
    class TickTock {
    synchronized void tick(boolean running) {
    if(!running) { // stop the clock
    notify(); // notify any waiting threads
    return;
    System.out.print("Tick ");
    notify(); // let tock() run
    try {
    wait(); // wait for tock() to complete
    catch(InterruptedException exc) {
    System.out.println("Thread interrupted.");
    synchronized void tock(boolean running) {
    if(!running) { // stop the clock
    notify(); // notify any waiting threads
    return;
    System.out.println("Tock");
    notify(); // let tick() run
    try {
    wait(); // wait for tick to complete
    catch(InterruptedException exc) {
    System.out.println("Thread interrupted.");
    }Message was edited by:
    Rix87

    A simple return statement means that you are just exiting that function. A function can use the return statement even if it is declared a void. It is just that from a void function you can not return a value.
    In your code the function is doing some condition checking (if statements) and based on that decides whether to exit the function or to continue going forward.
    Additionally, the if-construct is not a loop. If statements provide conditional branching mechanism.
    http://java.sun.com/docs/books/tutorial/java/nutsandbolts/branch.html
    You probably will never need to break out of an if statement. If you do need it, then perhaps your if condition is suspect.
    http://java.sun.com/developer/TechTips/2000/tt0613.html
    You can use labeled breaks if you need to break out of nested if statements but it is very rare that you will need them and the code can perhaps be written in another way which is much more readable than labeled breaks.

  • Why is a return statement similar to an assignment?

    Hey guys, quick question I was told that a return stament is very similar to an assignment does anyone know why we could say that?
    Best
    John

    They're similar in that they're both constructsin
    the Java language. Other than that, either theperson
    who told you this was smoking crack, or you
    misunderstood, or there's some significant
    context
    missing.That's not true. A return statement can be seen asan
    assignment to the method name.
    I don't think that's a very good analogy. Methods don't have values in the sense that variables do, and to try to picture them that way just muddies up other concepts. I think it's even less clear when you throw multiple theads into the mix.

  • Missing return statement. Why?

    Hi guys this might be an easy one for you all.
    I am receiving the error below when compiling the class below. Any idea what kind of statement I should be returning?
    Database.java:51: missing return statement
    ^
    1 error
    public Item search(String title){
         String ItemName;
         for (int i=0; i < items.length; i++)      {
             System.out.println (items);
    ItemName = items[i].getTitle(); // polymorphism
    if (ItemName.equals(title)) {
    System.out.println ("Match Exists!");
    } else {
    System.out.println ("No matches found");

    hi
    I am sorry to disturb u.this code will work fine .pls go throw the code.we have to add return statement in the two place.previously it was in loop only.Let me know the response pklease .public Item search(String title){
         String ItemName;
         for (int i=0; i < items.length; i++)      {
             System.out.println (items);
    ItemName = items[i].getTitle(); // polymorphism
    if (ItemName.equals(title)) {
    System.out.println ("Match Exists!");
    return items[i];
    } else {
    System.out.println ("No matches found");
    return null;
    return null;

  • Missing return statement

    Can anyone tell me why I'm getting a missing return statement error in this code?
    import java.awt.*;
    * Write a description of class Flower here.
    * @author (your name)
    * @version (a version number or a date)
    public class Flower
        protected FilledOval dot;
        protected FilledRect stem;
        protected FilledOval petal1;
        protected FilledOval petal2;
        protected static final int boundary = 100;
        protected RandomIntGenerator colorGen =
                new RandomIntGenerator(0,255);
        protected Color petalColor;
        protected Boolean flowerContains=false;
        private DrawingCanvas canvas;
        public void changeColor(Location point){
        dot = new FilledOval(point,15,15, canvas);
        dot.setColor(Color.YELLOW);
        petalColor = new Color(colorGen.nextValue(),
                                    colorGen.nextValue(),
                                    colorGen.nextValue());
        petal1.setColor(petalColor);
        petal2.setColor(petalColor);
        public void grow(Location point){
        stem = new FilledRect (dot.getX()+3, dot.getY()+10, 10, 10, canvas);
        stem.setColor(Color.GREEN);
        if (dot.getY()>boundary){
            dot.move(0,-4);
        else{
         petal1 = new FilledOval(dot.getX()-12, dot.getY()-25, 40,70,canvas);
         petal2 = new FilledOval(dot.getX()-25, dot.getY()-10, 70,40,canvas);
         dot.sendToFront();
         stem.sendToBack();
         petal1.setColor(petalColor);
         petal2.setColor(petalColor);
        public Boolean flowerContains(Location point){
            if (petal1.contains(point)){
                return true;
            else if (petal2.contains(point)){
                return true;
            else if (dot.contains(point)){
                return true;
    }

    public Boolean flowerContains(Location point){
            if (petal1.contains(point)){
                return true;
            else if (petal2.contains(point)){
                return true;
            else if (dot.contains(point)){
                return true;
        }That method returns a Boolean value. But if none of the condition gets satisfied then what is it going to return?

  • Using return statement in jsp

    Hi all,
    I am using return statement in JSP page after a redirect to stop executing that page. If the data bean is not present then it must go to previous page. When this return statement is executed the previous page is displayed but url in browser remains same. Why it is so ?. Is there any other way to tell a JSP page to stop executing and redirect to another page.
    rgds
    Antony Paul

    Hi Antony,
    do you use the "forward()" method or the "redirect()" method???
    rgds
    Howy

  • Missing return statement - Java noob here

    Hi to everyone! I'll just like to ask if anyone of you can check out my code and see why I can do to correct this 'Missing return statement' problem with my code.
    From what I've been noticing, the compiler returns this statement when the return statements are inside conditional clauses. Usually I've been able to remedy it by storing it into another variable that's been instantiated outside my usual 'if' statements. But this time, it was my first time to use a 'try' statement since FileReader and FileWriter won't work without it. I tried to use the same remedy but it just doesn't work. Here's the part of the code I'm having problems with:
    public String[] sortWordList()
             try
                  FileReader fReader = new FileReader("initlist.txt");
                  BufferedReader bReader = new BufferedReader(fReader);
                  String output = bReader.readLine();
                  String[] words = output.split(",");
                  for(int counter1 = 0; counter1 < words.length; counter1++)
                        for(int counter2 = counter1 + 1; counter2 < words.length; counter2++)
                                  if(words[counter2].compareToIgnoreCase(words[counter1]) < 0)
                                       String temp = words[counter1];
                                       words[counter1] = words[counter2];
                                       words[counter2] = temp;
                   String temp = "";
                   for(int counter1 = 0; counter1 < words.length; counter1++)
                        FileWriter fWriter = new FileWriter("initlist.txt");
                       fWriter.write(words[counter1] + "," + temp);     
                       fWriter.close();
                       temp = bReader.readLine();
                   String output2 = bReader.readLine();
                  String[] words2 = output.split(",");
                  return words2;
             catch(IOException ioe)
        }The compiler points the 'Missing return statement' at the last bracket.
    BTW, just for those who are wonder what we're making, our teacher gave us a machine project where we have to make a basic dictionary (words only, we'll be doing the definitions and other stuff that's associated with the word some other time I think) with input and sort functions.
    Thanks guys!
    - Alphonse

    T.B.M wrote:
    By doing this, we're subverting the exception mechanism and totally defeating the purpose of exceptions. If you're going to catch an exception, you should handle it. Just smothering it and returning null is not handling it. If you're not going to handle it, then don't catch it, or else catch it and wrap it in a more layer-appropriate exception and re-throw.Then ideally there should be some *"return String[];"* statement inside "catch", not after it.No. Not unless there's some meaningful default value to use when the file can't be read, which does not appear to be the case here.
    If you return null, or an empty String[], then the caller will have to do an if test to know that something went wrong and that the method failed to do what it was supposed to do, and then what is the caller supposed to do in that case? The point of exceptions is to avoid those explicit tests for errors and let the "happy path" code just go on under the assumption that things are fine. If something goes wrong, an exception will be thrown and the happy path code will stop excuting, without having to explicitly test for an error condition.

  • Missing return statement error! HOW?

    Why would the following code complain that it's missing a return statement, yet there are more than 4 return statements. All the possibilities are captured on the if statements and there are no more possibilities.
    public static double power(double b, int e)
            if(e == 0 || b == 1)
                return 1;
            else if(e > 0)
                if (b > 0)
                    return b * power(b, e - 1);
                else if (b % 2 == -1)
                    return -(power(b, -e));
            else if(e < 0)
                if(b > 0)
                    return 1 / power(b, -e);
                else if (b % 2 == 1)
                    return -(1 / power(b, -e));
        }Edited by: deyiengz on Jul 30, 2009 8:34 PM

    ejp,
    Thanks for the rapid response
    I thought there could only be these possibilities:
    1. e = 0 and b = 1
    captured in the 1st if statement
    2. e > 0 and either (b > 0 or b < 0)
    captured in the second if
    3. e < 0 and either (b > 0 or b < 0)
    captured in the Third if
    and else nothing else+
    What's remaining? This was meant to be easy, what the hell am I not seeing?
    flounder Thanks too for your response.
    I tried to remove the if on the last else if (below) but still got the error
    else
                if(b > 0)
                    return 1 / power(b, -e);
                else if (b % 2 == 1)
                    return -(1 / power(b, -e));
            }Edited by: deyiengz on Jul 30, 2009 9:14 PM

  • Missing Return Statement Hell!!

    public class EventSite
    private int siteNumber;
    public EventSite()
    siteNumber = 999;
    public int getSiteNumber()
    return siteNumber;
    public Void setSiteNumber(int n)
    siteNumber = n;
    I'm taking a java class and this won't compile...Whats wrong??
    Why the Missing return statement error?

    flounder wrote:
    NewProgramGirl wrote:
    no need it is now compiled, think it was the big "V'...thank you....soooo much!!Well that contradicts what you said in reply 4.I'm guessing we forgot the all important "Save" step of the development lifecycle.
    Speaking of development lifecycle my version control system at my new job consists of zipping my project to the main fileserver each night before I leave. Apparently the SVN will be set up any day now...

  • Missing return statement?  News to me!

    Before I ask anything let be begin by saying thanks to all you people that help others on these boards, I've never posted a question before but I have often found the answers to my problems somewhere here. I'm currently working on one of my last java assignments ever and I am completely stumped as to whats going on. All I want out of this code is for it to read a txt file for a bunch of phone book entries, load them into some arrays, then sort them by first name, last name, then phone# then return the array so I can use it later on. I've got the entries loaded, I've got em sorted, but I can;t return it. When I try I get a missing return statement error. I dont know why its not returning the array, so I thought I'd ask the pros. I can get it to work fine if I dont return anything but what good is that eh?
    Please forgive my terrible coding, I am in no way a real programmer, I just want to pass my classs and never think about it again 8) any help would be appreciated. Tis is built to work with an "Entry" file, if you guys need it to proceed lemme know and I will post it. Thanks.
    the code....
        public class CSCD210PhoneBook {
           public static void main(String[] args)throws IOException
          {//Opening main          
             Scanner kb = new Scanner(System.in);
               int entryCount=0;
                   Scanner fileScanner=null;
                   Entry[] array=null;
         array=populateEntry(entryCount, fileScanner, kb);
          }//end main array=
                 public static  Entry[] populateEntry(int entryCount, Scanner fileScanner,Scanner kb)throws IOException
                    int lineCount=0;
                   String fileName;
                   File fileHandle;     
                   System.out.println("Which file would you like your entries pulled from?");
                   fileName= kb.nextLine();
                               fileHandle = new File(fileName);
                   fileScanner = new Scanner(fileHandle);
                   while(fileScanner.hasNext())
                         fileScanner.nextLine();
                         lineCount++;
                   entryCount= lineCount/8;
                   Entry[] array=new Entry[entryCount];
                   fileScanner.close();
                   fileHandle = new File(fileName);
                   fileScanner = new Scanner(fileHandle);
                        for(int i =0; i<array.length;i++)
                             array=new Entry(fileScanner);
                   fileScanner.close();
                   int curPos, indexSmallest, start;
    Entry temp;
    for (start = 0; start < array.length - 1; start++)
    indexSmallest = start;
    for (curPos = start + 1; curPos < array.length; curPos++)
    if (array[indexSmallest].compareTo(array[curPos]) > 0)
    indexSmallest = curPos;
    } // end for
    temp = array[start];
    array[start] = array[indexSmallest];
    array[indexSmallest] = temp;
                   return array;
    Any help would be most appreciated.

    The code you posted has mismatched braces: it needs another } at the end.
    Linked with this is how - or rather when - you return array from the populateEntry()
    method. You have a couple of nested for-loops and you return array inside (at the
    end of) the outer loop.
    The compiler is really fussy about making sure that an Entry[] is returned from this
    method. If you outer for-loop never gets executed for some reason, then the return
    statement will never be reached. The compiler won't accept this.
    Either
    (1) move the return statement outside both loops so it is always executed. This
    appears to be the most logical thing - but I haven't read your code that closely. It's
    just that having return at the end of a for-loop (with no "continue" in sight), doesn't
    make a lot of sense.
    or
    (2) add another return after both loops have finished.

  • Return statement in exception and consequences

    Hi,
    Can any one give me the explanation for my doubt?
    Case 1:
    I am having some code throwing some exception lets say arithematic exception in my try block.
    I caught it in the catch block and at last I am having one finally?
    as per normal order try block next catch block and at last finally will execute.
    I execute the above code by putting a return statement inside catch block.I got the same order of execution irrespective of return statement inside catch?
    What is the significance of return inside catch?
    Case 2:
    Lets take the scenario.
    class MyException
         public static void main(String[] args)
              int i=1,j=0;
              try
                   try
                   System.out.println("the value is: "+(i/j));
                   System.out.println("Inside try block");
                   catch(ArithmeticException e)
                   System.out.println("hi in ame");
                   //return;
              finally
              System.out.println("inner finally");
                                            System.out.println("outer try");
              catch(Exception e)
                             e.printStackTrace();
                   System.out.println("in exception");
              finally
                   System.out.println("plz wait");
    If return statement is there inside the inner try and catch the code out of inside outer try not getting executed Why So?
    Any clarifications?
    Thanking you,
    Murthy.

    First, please format your code as per http://forum.java.sun.com/features.jsp#Formatting
    I'm not sure what part you don't understand.
    .    public static void main(String[] args) {
    .        try {
    .            try {
    .                throw new ArithmeticException();
    .                System.out.println("Inside try block"); // #1
    .            catch(ArithmeticException e) {
    .                System.out.println("hi in ame"); // #2
    .                return;
    .            finally {
    .                System.out.println("inner finally"); // #3
    .            System.out.println("outer try"); // #4
    .        catch(Exception e) {
    .            System.out.println("in exception"); // #5
    .        finally {
    .            System.out.println("plz wait"); // #6
    .    }#1 -- You won't get here because you throw AME.
    #2 -- You will get here because you caught the AME you just threw.
    #3 -- You will get here because it's a finally
    #4 -- You won't get here. I think that this is what you're asking about: Why don't we get here? Because we've already done 'return' and this line is NOT inside a finally. The only things that can get executed after a return are finally blocks.
    #5 -- You won't get here because you already caught the AME and didn't rethrow it or any other exception.
    #6 -- You will get here because it's a finally.
    Once you do a return, the only code you can execute before exiting the method are finally blocks. First the one corresponding to the try/cathc block where your return is, then the finally for the try/catch that encloses that one, and so on outward. The code between one finally and the next (#4 here) is NOT executed.
    If you still have a question, please try to clarify exactly what behavior you don't understand.
    Don't return from inside t/c/f.

  • RETURN statement "kills" my BSP event handling

    Hi,
    I've gone through [this|Downloaded Excel data is shown using Chinese characters (!); and everything went just fine. At the end of that code, to make my BSP react and finally display that popup, I had to insert a RETURN statement, and by doing so, the BSP virtually "dies": stops reacting to any ohter event, and finally makes me close the browser. This is the relevant section of my code:
    cFolders
    OnInputProcessing event
    response->set_data( data   = lv_xstring ).
    navigation->response_complete( ). " signal that response is complete
    return.
    Why is that happening? What could I do to avoid that behavior, and keep working my custom pushbutton functionality?
    Thanks in advance, hope someone could help me.
    Regards,
    Federico.

    Hi Frederico,
    I think there is a misunderstanding, what you want your application to do and what response_complete is used for.
    Do I understand your requirement right: You want a popup-window with excel content and in background-window the standard application should run unchanged?
    That doesn't work with response_complete in OnInputProcessing, because the statement is used to prevent creating the default response of a page in onLayout method
    If you use RETURN, the processing of your page is stopped and the response consists only of the content you filled in but not of any default page layout => excel appears but your application seems to be dead
    If you do not use RETURN, you navigate to another page (statement cl_cfx_util_ui=>navigate). As navigation in BSPs is realized by a browser redirect, a complete new request-response-zyklus is started => no excel appears, your response seems to be overwritten
    Possible solutions are:
    1. Instead of sending the response object back to the client, store it in the server-cache (method SERVER_CACHE_UPLOAD of class CL_HTTP_SERVER) in OnInputProcessing and open a new browser window with url of object in server-cache.
    OR
    2. Open a new browser window with url of a new custom bsp page and generate the response in onInitialization of the new custom page.
    Search the forum, you'll find a lot of examples how to use the server-cache and how to open a new window with javacript.
    Anyway: read also SAP help to understand the control flow of BSPs: [http://help.sap.com/saphelp_nw70/helpdata/en/a3/4b9afa7aa511d5992e00508b6b8b11/frameset.htm] 
    Best regards,
    CW

  • Return statement inside AddEventListener?

    I am writing a custom function that will add a component to
    the stage. However, I want to postpone adding this component until
    some data has been loaded. Problem is that placing the return
    statement inside the Event handler function won't work, because it
    would be interpreted as a return statement for the Event handler
    function. Is there a way to for instance refer to the parent
    function?

    "Jurgen Beli?n" <[email protected]> wrote in
    message
    news:gq7jbs$7i4$[email protected]..
    >I am writing a custom function that will add a component
    to the stage.
    >However,
    > I want to postpone adding this component until some data
    has been loaded.
    > Problem is that placing the return statement inside the
    Event handler
    > function
    > won't work, because it would be interpreted as a return
    statement for the
    > Event
    > handler function. Is there a way to for instance refer
    to the parent
    > function?
    >
    > private function addDrawer(...):Drawer {
    > var newDrawer:Drawer = new Drawer();
    >
    > drawerContentLoader.addEventListener(Event.COMPLETE,
    function
    > (event:Event):void {
    > newDrawer.DrawerContentXml =
    XML(drawerContentLoader.data);
    >
    > // return newDrawer when loaded.
    >
    > });
    > drawerContentLoader.load(drawerContentRequest);
    >
    > return newDrawer;
    > }
    Why not just put your logic inside the handler for the event
    where the data
    exists for you to actually be able to populate it?

  • This should work? error missing return statement.

    Why do I get this error?
    missing return statement
    To me the code seems good?
    public SortAbstractProduct createSorter(String whichAlgorithm) {
    if (whichAlgorithm.equalsIgnoreCase("BubbleSortProduct") )
    System.out.println("from scf buublesort check");
    return new BubbleSortProduct();
    if (whichAlgorithm.equalsIgnoreCase("OptimsedBubbleSortProduct") )
    System.out.println("from scf optimesed buublesort check");
    return new OptimisedBubbleSortProduct();
    if (whichAlgorithm.equalsIgnoreCase("QuickSortProduct") )
    System.out.println("from scf Quicksort check");
    return new QuickSortProduct();
    }

    You need to retrun an object of SortAbstractProduct, yet your are trying to return 3 different types(BubbleSortProduct, OptimisedBubbleSortProduct, QuickSortProduct). These need to be subclasses of SortAbstractProduct, then you will be able to cast them it.

  • Doubts reg try block and return statements

    hi
    public int test()
              try
                   System.out.println("hi");
                   return 1;
              catch(Exception e)
              System.out.println("err");
              return 2;
              finally
                   System.out.println("final");
                   return 3;
              //System.out.println("after");
              //return 4;
    when i call this function, it will printing 3... why ??
    and also compilation error is coming when i put return statement after final block.. why is it so??

    but if commented the return statements in catcch and finally then it iam not getting any compilation error.
    public int test()
              try
                   System.out.println("hi");
                   return 1;
              catch(Exception e)
              System.out.println("err");
              // return 2;
              finally
                   System.out.println("final");
              //     return 3;
              System.out.println("after");
              return 4;
    and iam just learning ..... regarding return and try block

Maybe you are looking for