simple method of max

Hello

I'm doing a simple method that returns the maximum element of an array of int. (I got this question on an interview.)
I want to do it properly, so my question is what do I do if the table is null? Is there a common solution, best practices for this?
Can I use try-catch block for NullPointerException or just an if-else?

Also please tell me if my method is correct otherwise.

Thank you!
     public static int max(int[] arr) {

          if (arr == null) {
               ????  //System.out.println("array is null");
               ????  //return Integer.MIN_VALUE;
          } else {
               int temp = Integer.MIN_VALUE;
               for (int i : arr) {
                    if (i > temp)
                         temp = i;
               }
               return temp;
          }
     }

lemonboston wrote:
Hello

I'm doing a simple method that returns the maximum element of an array of int. (I got this question on an interview.)
I want to do it properly, so my question is what do I do if the table is null? Is there a common solution, best practices for this?

It depends on the specific context, but have no other details, I'd throw an IllegalArgumentException or NullPointerExcecption. I'd also throw IllegalArgumentException if the array has zero element.

I certainly would NOT return any value unless the requirements specifically said that this is the desired behavior.

Also please tell me if my method is correct otherwise.

The loop to find the max value in the case of a valid table looks good. The only things I would change are:

(1) rename the temp into something more meaningful, such as max or result.

2) put braces around the temp = i body of the if (I > temp) test. They are not strictly necessary, but I (and most of the people I know) feel better to always use. Avoids confusion, makes it clear that you really don't want only this line in the body and prevents the error from adding more lines later and forget to add the braces.

Tags: Java

Similar Questions

  • Y at - it a simple method to move the new images in an album existing?

    I don't understand why it must be so difficult just to get a new image into an existing album! It seems to me that Adobe has created a simple workflow method to accomplish this simple task. After watching of many FAQ questions / answers, it looks like a number of people have asked the same question but also received a large number of responses of type "get around" to move the images in an existing album.

    For example, one method was to create a new album with a smilar name, then merge the album into existing 'main' album. There must be an easier way to get this done.

    Thank you.

    Happy to help you.

  • A simpler method of dividing or clipping mask?

    OK, I'm back with a new question. Design to go on Tshirt

    NOT CE DESIGN, just example.

    Shirt color shows while creating lines in the gun (indicated by black background)

    Here I have a firearm on a locked layer black background. All the white parts of the pistol

    are their own forms, grouped. (so the gun rest the gun.)

    As you can see, with a pistol on the right, the black background (color of the shirt) shows

    by creating the outline of the gun.

    Now, I want to overlay of this indicator on the gun to fire at

    where it seems that the gun has a flag on this issue.

    2016-01-11_23-45-00.jpg

    Now here's a clipping mask. Yes it works, but for what I do. I can't have paths in the background

    that make up the flag. No extra charge no matter what, just the barrel and research as it has a flag. Clipping path

    method also creates a larger file. For screen printing on t-shirts, these additional lines of the invisible flag

    can cause a problem.

    2016-01-11_23-46-34.jpg

    Divide then works fine. I put the gun in the back, the flag on the front and divide. Then ungroup.

    In the image below, I've removed many of the parts of the Pavilion which were divided.

    However, then I have to hunt for the paths that I want to be transparent (so shirt shows through lines).

    It takes a lot of time. You can see that I chose a piece inside the drum of spinning, where the bullets are going inside.
    This piece is deleted, like many others, up to what the black shirt color indicates where to, once again.

    2016-01-11_23-57-02.jpg

    There must be an easier way to do it. So he superimposed the indicator only on the white of the forms that make the gun
    as a clipping mask, but where I can remove all paths associated with the parts of the flag I don't need.

    Notice to lovers?


    This is exactly the situation I have right now. I have a skull that I need to superimpose a flag on.

    I THOUGHT WITH A WORKAROUND... I'M A GENIUS!

    Thus, while brainstorming, I think I have a better method.

    We will use a black background as a cutter.

    With the help of a black background even size as a document.

    With the help of skull original to cut through leaving the black. (select skull and black background then split)

    Edit > cut black (who is a master of cutting everything that needs to be transparent.) now in the Clipboard

    Put the flag in the document, paste black flag.

    Select Black punch and flag.

    Divide

    Ungroup

    Select same fill color (by selecting the black hole)

    Delete

    ALTO! Left with all the pieces that have the color of the flag.

    ALL VECTORS. Reduced file size.

    I'M A BEAST!

    I now use cookie cutter method on all the models that I had.

    and it's considerably allowing a reduced file size.

    Mainly because there is only one group, which contains all the parts

    that make up the drawing.
    With the help of text and expand on the text damaged by arches, which had created grunge effects

    large file formats.

    Maybe all that could be cleaned.

    However, this method is so easy.

  • Y at - it a simple method to disable and flatten graphical objects in the .pdf file?

    I often send .pdf files to my clients. I do not protect the files because it seems that I do not trust my clients

    I do generally two types of activity:

    (1) change a Word file where to paste my graphic signature, then export it in. PDF. Unfortunately, my graphicla signature object is always there, and anyone with Acrobat can enter.

    (2) modify the existing Acrobat files where I hide parts of the page with white spots. I print the files in. PDF, but the patches/items are still there and anyone can remove.

    I can protect the file, but there not a method to flatten objects and make them NOT SELECTABLE at all? I don't care if surrounding text does not become achievable OCR.

    I tried with optimization and deleting objects, but no way to success.

    I'm sure there's a solution, but I was not able to find it.

    Thank you

    Paolo of Italy

    You do not trust of your customers. You fear that they can somehow extract the content and use it in a way that is detrimental to you. If something is in PDF format, it can be extracted, even if you apply security. Addition of security will make impossible to extract or modify the content with Acrobat or any other Adobe software.

    On the contrary if obscuring the content with the white objects, use the writing tool to remove content completely. You can configure the properties of redaction to set fill in white color.

  • Simple method of appeal of multiple OS in VO problem

    Hi all

    Have a little problem.
    Use case:
    1. the user call method updateSalary
    2. run updateSalary and insert the new salary in another table, call the method saveChangedSalary of EO another

    My methods:
    EO method:
    Employees
    {} public void updateSalary (Double p_money)
    Double p_salary = this.getSalary () .doubleValue ();
    p_salary = p_salary + p_money;
    this.setSalary (new BigDecimal (p_salary));
    }

    Method SalaryHistory:
    {} public void saveChangedSalary (ob EmployeesImpl)
    this.setSalaryId ((new oracle.jbo.server.SequenceImpl ("EMPLOYEES_SEQ", this.getDBTransaction ()) .getSequenceNumber () .intValue ());
    this.setSalary (ob.getSalary ());
    this.setEmployeeId (ob.getEmployeeId ());
    this.setCommision (ob.getCommissionPct ());
    Calendar cal = Calendar.GetInstance ();
    Timestamp = new oracle.jbo.domain.Timestamp (new oracleDate
    java.sql.Timestamp (cal.getTime () .getTime ()));
    this.setDateChange (oracleDate);
    }

    Methods of VO: (I think that's my problem, do not know how to create the new object of the HS)
    EmployeeVORowImpl:
    public void updateSalary (row, Double p_money) {}
    / * This works fine * /.
    EmployeesViewRowImpl r_object = (EmployeesViewRowImpl) rank;
    EmployeesImpl e_object = r_object.getEmployees ();
    e_object.updateSalary (p_money);

    / * SalaryHistoryImpl e_salary_history = new SalaryHistoryImpl();
    e_salary_history.saveChangedSalary (e_object); * /

    / * Problem, if this isn't a ples writh right one way * /.
    SalaryHistoryViewImpl row_im = new SalaryHistoryViewImpl();
    Line dupRow = row_im.createRow ();
    SalaryHistoryViewRowImpl shvri = dupRow (SalaryHistoryViewRowImpl);
    SalaryHistoryImpl e_salary_history = shvri.getSalaryHistory ();
    e_salary_history.saveChangedSalary (e_object);


    }




    Tahnk you for you time

    You do not get an instance of SalaryHistoryView in the correct manner. You should not create VO instances manually (as you did in the updateSalary() method). The following are some ways correct to get the necessary instance of VO:

    * #1: set the SalaryHistoryView in the data model of the same ApplicationModule and get an instance of VO by name through the AM: *.

     // Supposing that the VO was defined as "SalaryHistoryView" name in the AM's data model
    SalaryHistoryViewImpl vo = (SalaryHistoryViewImpl)am.findViewObject( "SalaryHistoryView");
    SalaryHistoryViewRowImpl row = (SalaryHistoryViewRowImpl)vo.createRow();
    ...
    

    * #2: create a ViewLink of master / detail between the EmployeesView and SalaryHistoryView (where EmployeesView is the master and SalaryHistoryView is the detail). Expose this ViewLink as an accessor in EmployeesViewRow. Use the EmployeesViewRowImpl accessor class to get the RowIterator to the instance of SalaryHistoryView detail: *.

    // Within EmployeesViewRowImpl class and supposing that the accessor's name is SalaryHistory
    RowIterator rowiter = this.getSalaryHistory();
    SalaryHistoryViewRowImpl row = (SalaryHistoryViewRowImpl)rowiter.createRow();
    ...
    

    Dimitar

  • Simple method to check if the network is available to open HttpConnection

    So I read around, and I found that you can not change the time of 2 minutes by default for HttpConnection, and you should check to see if a connection is available first before attempting to connect. I tried almost everything I can think of, and I can't imagine it being more than a few lines of code. Here's what I do. He never thinks that a connection is available. Haven't tested on a device.

    //TODO: Determine if this works on a device!
    if(DeviceInfo.isSimulator()){
        if(!CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_MDS)){
          xmlParseProgress.processError(ObserverInterface.ERROR, "No Connection");
          return false;
        }
    } else {
        if(!CoverageInfo.isCoverageSufficient(CoverageInfo.COVERAGE_DIRECT)){
          xmlParseProgress.processError(ObserverInterface.ERROR, "No Connection");
          return false;
        }
    }
    
    //http = (HttpsConnection)Connector.open(url+GlobalVars.getConnSuffix());//etc
    

    Can someone give me the code that works?

    Thank you!

    That's what I'm use to check if a connection is available, hope this helps someone:

    public static boolean canConnect(){
        return !(CoverageInfo.isOutOfCoverage() ||
                RadioInfo.isDataServiceSuspended());
    }
    
  • Simple method to display the pictures stored external oracle xe, in a region of html

    Hallo!

    I've created an html area on my Apex (4.0.1) pages and I want to display an image (and), which is stored in a folder of OS inside this region!

    What is the easiest way to do this?

    Is it possible using the URL or better through B-file.

    There is here a small tutorial or any code sample?

    Thank you

    Hello

    Here's how you can show images from the folder on the server:

    This is just example and suppose you create the new application.
    I assume that your XE database is windows machine.

    Connect to SQL plus as SYS and create the directory

    create directory my_img_dir as 'c:\my_images\';
    

    Grant privilege read on directory (ANONYMOUS) user to DAD

    grant read on directory my_img_dir to anonymous;
    

    Grant privilege read on directory to your application to the analysis of schema. Modify the "my_schema".

    grant read on directory my_img_dir to my_schema;
    

    Create the new application and 2 blank pages. I guess the first page (id 1) is where you show images.
    Second page (id 2) is just for the appeal process.

    Create point of application process "on the cloth: before the header."

    DECLARE
      l_lob     BFILE;
      l_length  NUMBER;
    BEGIN
    --
      l_lob :=  BFILENAME('MY_IMG_DIR', :REQUEST);
      l_length := DBMS_LOB.getlength(l_lob);
      --
      htp.flush;
      htp.init;
      --
      htp.p('Content-length: ' || l_length);
      --
      htp.p('Content-Disposition: filename="&REQUEST."');
      --
      -- close the headers
      owa_util.http_header_close;
      --
      -- download the BLOB
      wpg_docload.download_file(l_lob);
    --
    END;
    

    Make the process conditionally if the page is 2.

    Region HTML on page 1 to create and place the source of the region

    
    

    Replace "my_picture.gif" with the name of the image you have in the folder c:\my_images. The image name is case sensitive

    Kind regards
    Jari

    Published by: jarola November 18, 2010 02:36

    I notice that you mention your OS.

    Above statement replace c:\my_images\ by/var/my_images for example.
    Make sure that "others" have read permission on folder and files it contains the image.
    Group and owner of the folder can be for example root

  • Simple method for another server videos

    I am a newbie to FMS and I tried searching forums, as well as Googling to do this, so please forgive my ignorance.

    I've got:

    -Already installed FMS on XP with IIS server

    -Video FLV, residing in a folder on another server

    How do I:

    Videos of the other server where are the videos?

    Thank you!

    Please see: network folders mapping drives on this page - http://help.adobe.com/en_US/FlashMediaServer/3.5_AdminGuide/WS5b3ccc516d4fbf351e63e3d119f2 925e64 - 7fc7.html -it might be useful

  • OnRelease simple method does not-why?

    I have a nav system I'm developing and here is a piece of code. Everything works well except the onRelease will not work. Any ideas, help would be a life saver. Thank you!

    this.onEnterFrame = function() {}
    If (main_nav_mc.mag_nav_mc.hitTest (this ._xmouse, this ._ymouse, true)) {}
    main_nav_mc.mag_nav_mc.gotoAndStop("on");

    If (main_nav_mc.mag_nav_mc.mag_subnav1_mc.hitTest (this ._xmouse, this ._ymouse, true)) {}
    main_nav_mc.mag_nav_mc.mag_subnav1_mc.gotoAndStop("on");

    main_nav_mc.mag_nav_mc.mag_subnav1_mc.onRelease = function() {}
    getURL ("web address here", _blank);
    }

    } else {}
    main_nav_mc.mag_nav_mc.mag_subnav1_mc.gotoAndStop ("OFF");
    }


    main_nav_mc.mag_nav_mc.onRollOut = function() {}
    main_nav_mc.mag_nav_mc.gotoAndStop ("OFF");
    }
    }

    OK, I tweaked this a bit further trying to get each film subnav be clickable. I think I have it working properly. Do you see not any problem with that? Thank you!

  • Min - Max and the planning of Kanban

    What are the factors or business cases that should be considered in the choice of planning that we should go?
    Any help would be appreciated

    My Client is interested in the above 2 methods

    Thank you
    Mahendra

    It of a broad question and is not easy to answer.
    One major difference is your philosophy.
    Kanban (if properly implemented) is pull based system.
    Min - max is always anxious that is it looks at your current onhand, future demand, future supply and then comes up with a purchase requisition.

    But there is no hard rule.

    Min - max works well when the issue of subinventory is not placed in a compartment. But in a workshop type of situation, you can have an operator goes the CRUDE inventory to get a bucket of screws.
    If you ran min - max on the WIP subinventory, he will think that you have a lot and does not generate a purchase requisition.
    But another operator may require that these screws and it may be out of them. In this case, a Kanban work better because as soon as the first operator took the last nth bucket, Kanban would have triggered the replenishment process.

    Kanban requires you to spend the time to analyze your problems to get to many of bin sizes and locations.

    The general rule is that Min - Max is simpler to implement.
    Kanban is a bit more complicated. So if your organization is not not mature enough or requires a simpler solution, min - max will work better.

    Sandeep Gandhi

  • Use a persistent storage or other methods to synchronize

    I have a user interface class that communicates with a background class by sending commands with world events to the base class. Two of them also uses a persistent storage.

    A simple method to retrieve return values could be to use a persistent as this storage:

    The user interface does:

    1 clears the back entrance in a persistent storage

    2 send the world event.

    3. going in a loop with a Thread.sleep and check if the back entrance is always empty

    After a number of loops decides that no response will be provided.

    The background task does:

    1 housing starts by accessing persistent storage in order to block with synchronization

    2 performs at the request of action

    3 put the result in the return of persistent storage field

    4 out of sync

    It sorts of handset return results and waiting for results. If the background task is not there the user interface will break out of the loop with a blank back. The only uncontrolled situation would be if the background task fails

    along the way, but then I have other problems. I threw an eye to wait/notify, semaphores and others, but the easiest solution is to use a persistent storage, because it has been used in any case for return information.

    Or expertise in this forum suggest another approach?

    A single Thread.yield is very good indeed, but if you put the user interface in a loop, just treatment Thread.yield () and the test for completion, instead of blocking your Thread event you will be hogging your event Thread and the operating system can get mad that too.

    As to notify the Ui that a message has been processed, Yes, the Observer Interface to do this.

  • TUNING METHODS

    Can someone please tell me in simple language on performance tuning methods. Please do not give online as reference doc.

    904298 wrote:
    Can someone please tell me in simple language on performance tuning methods. Please do not give online as reference doc.

    Watch an action (for example, a SQL statement), determine the duration of this action, identify what part of this time is spent waiting for resources and what part is working actively towards the completion of the action.

    Performance optimization is simply minimize the waiting time for the resources and make more effective, active work in will not affect anything else in the environment.

    In other words: find out why it is slow, came up with some ideas how to speed up, try the ideas and duck when others cry out that their role is now slowing down.

    ... Simple methods: use all the tools available to determine the component/length of time and then use the tool between your ears to determine possible solutions. It is based on experience.

    Published by: Hans Forbrich on March 8, 2012 12:41

    Moreover, the experience begins by reading. Reading specific manuals. :-)

  • Form validation - best method?

    Hi all

    Just curious what people think is a good and simple method of form validation, we can use these days. BTW: I know some php if that helps...

    PHP validation is certainly the best way to do it, and using the native PHP filters makes it almost too easy. You know about them?

    http://NET.tutsplus.com/tutorials/PHP/sanitize-and-validate-data-with-PHP-filters/

  • [PS CS4] Method of the hasTransparency() layer?

    Hello

    I need to check whether or not a transparent layer

    pixels. I searched the forums, but all the issues are on

    loading/modification transparency/layer masks, and I can't

    seem to understand how to translate all of the brilliant tips

    in a simple method of hasTransparency().

    I have downloaded xbytors xtools but lost in all the code...

    Can any of you give me a kick in the right direction?

    Thank you.

    Rasmus

    You can try this...

    alert(hasTransparency());
    function hasTransparency() {
        var desc52 = new ActionDescriptor();
            var ref47 = new ActionReference();
            ref47.putProperty( charIDToTypeID('Chnl'), charIDToTypeID('fsel') );
        desc52.putReference( charIDToTypeID('null'), ref47 );
            var ref48 = new ActionReference();
            ref48.putEnumerated( charIDToTypeID('Chnl'), charIDToTypeID('Chnl'), charIDToTypeID('Trsp') );
        desc52.putReference( charIDToTypeID('T   '), ref48 );
        desc52.putBoolean( charIDToTypeID('Invr'), true );
        try{
        executeAction( charIDToTypeID('setd'), desc52, DialogModes.NO );
        }catch(e){return false;}
        activeDocument.selection.deselect();
        return true;
    };
    
  • Adding a method to a data structure

    I want to add a method called max() to the table data type, so that I can say:


    var yData:Array = [885359, 804483, 747874];

    trace (yData.max ());

    The code to find the max is pretty easy, but I do not know where to place them.

    Any suggestions? Thanks in advance.

    professional air.  you just need to add:

    package com.mattmazur.utils {}

    If you have a website mattmazur.com.  that way your class, ArrayTools, comes into conflict with anyone else don't s ArrayTools class.

Maybe you are looking for

  • I need to recover my email after being hacked

    ease help meMy email account was stolen by a hacker, one called. He was using my account to e-mail until today and I hope that I can provide you with the enough information that can recover my stolen email. If I'm missing any information, please cont

  • write to the .xls file hourly

    Hello everyone! Feel free to help ! I have a small question about writing to the file. So basically I have to read 10 temperatures by 10 Thermocouples of a storage tank. I want to write in an excel file every hour. But the waveform is active all the

  • hpqwmiex Module stopped working

    I have problems, I cannot and could not update anything on my computer in about 2 weeks.  I followed many suggestions and it still does not work.  Belongs to this peoblem Module why?  What should I do, how do I do if I start getting updates again? Br

  • to listen during loading

    Is it a BAD IDEA to listen to the "rocket" while he is in charge, or an idea is NOT RECOMMENDED.

  • HotSpot of blackBerry Smartphones

    Dear BlackBerry community I had my BBTorch 9800 OS6 over a year now, which is a fantastic phone that complements any work that I do, that I use my phone as a modem. I find that sometimes I can have text, but it puts pressure on connection cards, when