Why do so many code samples here use Arrays?

I've seen many code samples here use Arrays. Why? I much prefer to use ArrayLists, and Vectors if I need synchronization or HashSets if I require uniqueness. I don't understand why people are using Arrays when the Collection classes are so useful. You can change the underlying datastructure without changing any of the access code.

I guess they are faster...
public class Test1 {
     public static void main(String[] args) {
            Integer zero = new Integer(0);
               long start = System.currentTimeMillis();
               for (int j = 0; j < 1000; j++) {
                    Integer[] array = new Integer[10000];
                    for (int i = 0; i < 10000; i++) {
                         array[i] = zero;
               long finish = System.currentTimeMillis();
               System.out.println(finish - start);
               start = System.currentTimeMillis();
               for (int j = 0; j < 1000; j++) {
                    ArrayList arrayList = new ArrayList();
                    for (int i = 0; i < 10000; i++) {
                         arrayList.add(zero);
               finish = System.currentTimeMillis();
               System.out.println(finish - start);
}~460 ms for array
~1600 for ArrayList
Still, the benefit of the Collections interface and the better OO design of code that uses these classes is probably worth it in most cases, IMO.

Similar Messages

  • Code samples for using HTTPServices in Cairngorm framework

    Hello there,
    Does anyone have any samples for retrieving data through
    HTTPServices using the cairngorm framework model. All samples on
    the web, as far as I have searched, lead only to remote services
    mode of communication only.
    Any help here would be greatly appreciated.
    Thanks,
    Arun B
    [email protected]

    I wrote a sample code modifiying the Remote Object examples
    .. I got this working now . Please ignore this message, just incase
    anyone needs my sample just email me..

  • Code sample for using change document function modules

    Can someone send me some sample code for using function modules CHANGEDOCUMENT_READ_HEADER and CHANGEDOCUMENT_READ_POSITIONS?  I'm specifically looking for changes that occured to the standard price field in the material master (MBEW-STPRS) and I need to pull the most recent price change for a given material.  I'm not sure how to write the code efficiently since I don't have a date to pass (again, since we're looking for the most recent change.)
    Thanks!

    hi check this..
    CHANGEDOCUMENT_READ_HEADERS
    Example:
    CALL FUNCTION 'CHANGEDOCUMENT_READ_HEADERS'
    EXPORTING
    objectclass = 'EINKBELEG'
    objectid = l_objectid
    username = space
    TABLES
    i_cdhdr = lt_cdhdr.
    LOOP AT lt_cdhdr WHERE udate IN s_aedat.
    CALL FUNCTION 'CHANGEDOCUMENT_READ_POSITIONS'
    EXPORTING
    changenumber = lt_cdhdr-changenr
    TABLES
    editpos = lt_editpos.
    LOOP AT lt_editpos WHERE fname = 'LOEKZ'
    AND f_new = 'L'.
    p_desc = text-r01. " Cancel Contract
    ENDLOOP.
    ENDLOOP.
    CHANGEDOCUMENT_READ_POSITIONS
    Example:
    CALL FUNCTION 'CHANGEDOCUMENT_READ_HEADERS'
    EXPORTING
    objectclass = 'EINKBELEG'
    objectid = l_objectid
    username = space
    TABLES
    i_cdhdr = lt_cdhdr.
    LOOP AT lt_cdhdr WHERE udate IN s_aedat.
    CALL FUNCTION 'CHANGEDOCUMENT_READ_POSITIONS'
    EXPORTING
    changenumber = lt_cdhdr-changenr
    TABLES
    editpos = lt_editpos.
    LOOP AT lt_editpos WHERE fname = 'LOEKZ'
    AND f_new = 'L'.
    p_desc = text-r01. " Cancel Contract
    ENDLOOP.
    ENDLOOP.
    Check this link.
    http://www.sap-img.com/mm001.htm
    <REMOVED BY MODERATOR>
    venkat.
    Edited by: Alvaro Tejada Galindo on Mar 18, 2008 4:05 PM

  • Why can I not sign in on my iPhone yet can sign in on here using my Apple ID?

    Anyone know why I can sign in on here using my Apple ID yet it won't let me on my iPhone 4S?? Software updated ages ago and not had a problem until now.... Any help greatly appreciated as I have lost access to my iMessages :-(

    Imessage and Facebook is down - Apple servers went down,  Wait a bit they are coming back on line....

  • Is there a RH standard for formatting code samples?

    In the RH default style sheet, I do not see a pre HTML tag or other tag that will display code samples in a monospaced font.
    I created custom styles for a single line code sample and another style for multiline samples.
    We want our code samples to be shaded. If I shade multiple lines, each line being separated with a paragraph, there is a small amount of
    white space between each line. We do not like this either.
    I then created a custom table style with a single shaded cell. I add my multiline sample code, then I apply the custom paragraph style to get
    the font and spacing between lines that I want.
    Is there a different best practice for this, so that the code sample would be rendered correctly if viewed from other devices that read the HTML and
    may look for the pre HTML tag?
    I am using RoboHelp 9 and I provide the output as Eclipse help. Our help files are integrated into Eclipse help in the Eclipse IDE.
    Thank you.
    Cynthia

    Hi Cynthia
    As much as it pains me to say it, this is one case where using a Form element might be your best bet. I say this because often code samples are used or presented with the intent of copying and pasting into something like Windows Notepad. And if you used the TextArea form element, you can place the code there and make it pretty easy for folks to copy it for use elsewhere.
    I stand to be corrected on this because I am not a "power CSS" person. (meaning I am aware there are complete two and three day classes one might attend on all the nuances of CSS) But RoboHelp won't really do anything to help you a great deal in formatting things. But it might be possible, somehow, to configure CSS to accomplish your goal of making the code look as you want.
    Cheers... Rick

  • Why now has a code to use the ipad with apple tv....

    Why now has a code to use the

    restart ipad
    http://support.apple.com/kb/HT1430?viewlocale=en_US&locale=en_US
    restart appletv (you can just pull the plug)
    restart the wifi router (you can just pull the plug unless the router documentation say otherwise)
    if it does not help then make sure that your wifi router is not using the same ssid (default is often netgear or linksys or whatever the brand is) as other close by wifi networks as that could result in 1 or more of your devices connecting to another network then you think they are using
    and if your wifi channel is the default if many close by wifi networks use the same channel it will cause disturbance
    and if your wifi network is running 2.4Ghz then it's a rather busy frequency dect phones, microwave ovens and tons of other things use the same frequency so if one have the option of changing to 5Ghz it's less busy == give less disturbances

  • Any code samples using StringWriter?

    I looked through the examples here and couldn't find one that used StringWriter. Does anyone know where a code sample using it can be found?
    Thanks

    OK... I got a small sample program to work but I am having trouble getting this one to work with StringWriter. I get an error on the line containing ---- s = new String(sw.toString); It says it can't resolve symbol. Here is the part of the code that is giving me trouble.
    try {
                   fin = new FileInputStream(args[0]);
              } catch (FileNotFoundException e) {
                   System.out.println("File not Found");
                   return;
              } catch (ArrayIndexOutOfBoundsException e) {
                   System.out.println("Usage: ShowFile File");
                   return;
              do {
                   i = fin.read();
                   if (i != -1) {
                        pw.print(i);                         
              } while(i != -1);
              fin.close();
              s = new String(sw.toString);
              StringTokenizer st = new StringTokenizer(s);     (I didn't put the import statements, variable declarations or main line for clarity). I also tried putting sw as the argument for StringTokenizer() as well and it didn' work.
    Any help would be great.
    Thanks

  • I dont know why the battery life of my iphone 4 is so low ! i really want to know how many hours i'll have if it's on standby. And how many hours if i use it normally for music and facebook (sometimes a little bit games)

    i dont know why the battery life of my iphone 4 is so low ! i really want to know how many hours i'll have if it's on standby. And how many hours if i use it normally for music and facebook (sometimes a little bit games) !!!

    to enhance your battery life, keep screen display to minimum, set screen lock automatically after 1 min, select internet notifications to off.

  • Please send me some sample codes of ALVS  using function modules only

    Hi,
    i am new to alvs
    Please send me some sample codes of alvs using function modules only.
    My mail id is [email protected]
    Thanks & regards,
    hari priya

    hI
    http://www.sapdev.co.uk/reporting/reportinghome.htm SPECIAL FOR ALL ALV PROGRAMS WITH EXAMPLE CODES
    Check the below links :
    http://www.sap-img.com/abap/sample-programs-on-alv-grid.htm
    http://www.sap-img.com/abap-function.htm
    http://www.sap-basis-abap.com/sapab034.htm
    http://www.erpgenie.com/abap/example_code.htm
    These all are very simple ALV programs ,good luck
    <b>Reward if usefull</b>

  • Code sample of sendRedirect using Web Dynpro NetWeaver 6.4

    Hi ALL,
      I’m building a Web Dynpro application under Netweaver Developer Studio 6.4 and I need to redirect to another URL while the client click on a button. 
      I know it should be something like request.getServletResponse(true).sendRedirect("myURL");
    But I’m not sure how to get the request, or the response in order to apply the sendRedirect method.
      Do you have any code sample or Web documentation I could use to redirect my Web Dynpro application?
    Best regards,

    Hello Jean-François,
    To navigate to http://www.yahoo.com you have 2 options:
    1) Call
    WDClientUser.forceLogoffClientUser("http://www.yahoo.com");
    2) Define Outbound plug with name Url in interface view, mark it as exit, define parameter Url with type String. Add usage of interface view in your view and add something like this in action handler:
    wdThis.wdGet...InterfaceViewController().wdFirePlugUrl("http://www.yahoo.com");
    Best regards, Maksim Rashchynski.

  • Why Can't I create an Appointment using this C# code?

    I have the following C# code and I'm getting an error (see below). Can anyone tell me what I am missing and why would I get an error at this point in the code?
    public static void Test()
    GroupwareTypeLibrary.Application groupwiseApp;
    GroupwareTypeLibrary.Account groupwiseAccount;
    object gwAppointment = "GW.MESSAGE.APPOINTMENT";
    object _missing = System.Reflection.Missing.Value;
    object egwDraft = 4;
    string mypassword = "abc123";
    groupwiseApp = new GroupwareTypeLibrary.Application();
    groupwiseAccount = groupwiseApp.Login("", "", mypassword, 0, _missing);
    //Create a New Appointment
    GroupwareTypeLibrary.Appointment7 appt;
    try
    appt = (GroupwareTypeLibrary.Appointment7)groupwiseAccoun t.WorkFolder.Messages.Add(gwAppointment, egwDraft, _missing);
    >>>>>>>>>>>> I get the following error on the line above
    >>>>>>>>>>>> "Object does not match target type." Any Ideas (i.e., what "type" should I use, See below the properties of the appointment I'm trying to set) ????
    catch (System.Exception ex)
    MessageBox.Show("Could not create Appointment item:\r\n\r\n" + ex.Message);
    return;
    appt.StartDate = DateTime.Now;
    appt.EndDate = DateTime.Now.AddMinutes(30);
    appt.AlarmSet = false;
    appt.Subject.PlainText = "This is the Subject";
    string messageID = appt.MessageID.ToString();
    string RetString;
    string cmdOpenMessage = "ItemOpen(\"" + messageID + "\")";
    GroupWiseCommander.GWCommander gwc = new GroupWiseCommander.GWCommander();
    gwc.Execute(cmdOpenMessage, out RetString);
    return;

    I solved the problem. The above code works fine if used alone, but I was also using the DevExpress.XtraScheduler control, and when I updated the GroupWise calendar items using a background thread, from that point on I couldn't talk to GroupWise at all. So I've rewritten my code not to use a background thread and it appears to be working fine.

  • Code sample using Oracle Provider

    Hi Is any got code sample using Oracle Provider with aspnet app

    Assuming your stored procedure is returning a REF CURSOR, it cannot be done. Oracle's REF CURSORS are read only constructs.
    Justin

  • Do we any T-codes to find  z-tcodes , how many times it has used?

    Dear Basis/abaper.
    Do we have any t-code to  find out the one z-tcode it has used till  date.
    If x user T-code:  z-y         ,used 1000 times.
    How to find out x user  used t-code  in production server.
    Please help me.
    Regards.
    Praveen Hazare.

    Dear Praveen,
    U can use STAD or ST03
    In ST03 click on Administrative - Expert ;mode -Total
    Hope this helps.
    Shri......

  • Code Samples??

    Ross - it's been over a monthsince any sample code has been posted. I know you guys are all about pushing professional services, but many times that is not an option, nor should it be, and we are sitting here stuck because the documentation is so poor and we are forced to depend on a Plumtree resource responding to a post to get our jobs done. We understand that sometimes code samples are incomplete and that would be a caveat, but even if you just throw us a bone by providing sample code of some of the advanced UI customizations you guys have done internally. Something, anything. The QuickStarts aren't sufficient and you only have 10 pieces total of sample code outside of the documentation, the latest sample posted over a month ago. Any news on when more is coming or what Plumtree's strategy is in that arena?
    Regards,
    Sarah Wheeler

    I have to completely agree with Sarah's post. I have read the EDK guide, the UI Customization guide (which drove me to read a Java manual, I'm a C# developer), Setting Up the Development Portal, every bit of the online documentation (quickstarts, sample code), and most of the posts on this discussion board. To recap, I have read, sometimes multiple times, every bit of available documentation around, specifically, UI Customizations and extending the Plumtree Application.
    This has done me no good, and has only proven to confuse me.
    I understand the Model-View-Controller design pattern; we use it for our ASP.NET development. Plumtree's implementation of MVC is tied so closely to the PT Server API that it is impossible to decouple the two. The UI documentation goes into some detail about activity spaces, views, models, and controllers, but never explains "why" they work in relation to the Plumtree Application. There are only loose references to Plumtree's implementation of MVC, and this is Plumtree documentation! To further the confusion (and the confusion runs deep), each piece of documentation I read seems to contradict all the other documentation I've read. The setup for Visual Studio development is almost laughable there are so many steps to follow, and once again, there is never any "why" to the "how".
    I really hope that PT comes up with some decent documentation and sample code to compliment what I'm sure is a very scalable architecture. Right now it seems like the blind leading the blind, not just here, but all over these discussion boards.

  • Creating a sample report using JAVA SDK

    Hi,
    I am trying to create a sample report using JAVA SDK.
    I slelect 4 "free cells" and pass 4 different strings to it.
    I even slelect the font colour and size. When i run the class and try to view the report in Infoview, I only seeblank blocks without any data. Now if I edit the report from infoview, and save the changes, I am able to see the data.
    My issue is, Why am I not able to see the data when I run the java code.
    Please find teh code below.
    package com;
    import java.awt.Color;
    import java.io.FileOutputStream;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import com.businessobjects.rebean.wi.BinaryView;
    import com.businessobjects.rebean.wi.DataProvider;
    import com.businessobjects.rebean.wi.DataProviders;
    import com.businessobjects.rebean.wi.DataSource;
    import com.businessobjects.rebean.wi.DataSourceObject;
    import com.businessobjects.rebean.wi.DocumentInstance;
    import com.businessobjects.rebean.wi.DocumentLocaleType;
    import com.businessobjects.rebean.wi.FontImpl;
    import com.businessobjects.rebean.wi.FreeCell;
    import com.businessobjects.rebean.wi.HTMLView;
    import com.businessobjects.rebean.wi.OutputFormatType;
    import com.businessobjects.rebean.wi.PageHeaderFooter;
    import com.businessobjects.rebean.wi.Query;
    import com.businessobjects.rebean.wi.Recordset;
    import com.businessobjects.rebean.wi.Report;
    import com.businessobjects.rebean.wi.ReportBody;
    import com.businessobjects.rebean.wi.ReportCell;
    import com.businessobjects.rebean.wi.ReportContainer;
    import com.businessobjects.rebean.wi.ReportElement;
    import com.businessobjects.rebean.wi.ReportEngine;
    import com.crystaldecisions.sdk.framework.CrystalEnterprise;
    import com.crystaldecisions.sdk.framework.IEnterpriseSession;
    import com.crystaldecisions.sdk.framework.ISessionMgr;
    import com.crystaldecisions.sdk.occa.infostore.IInfoObject;
    import com.crystaldecisions.sdk.occa.infostore.IInfoObjects;
    import com.crystaldecisions.sdk.occa.infostore.IInfoStore;
    import com.crystaldecisions.sdk.plugin.CeKind;
    public class Aug7th {
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              String CMS = "pundl8136:6400";
              String userID = "srivas";
              String password = "morcom123";
              String auth = "secEnterprise";
              List<String> entire =new ArrayList<String>();
              List<String> country =new ArrayList<String>();
              List<String> resort =new ArrayList<String>();
              IEnterpriseSession enterpriseSession;
              try
                   ISessionMgr mySessionMgr = CrystalEnterprise.getSessionMgr();
                   enterpriseSession = mySessionMgr.logon(userID, password, CMS,auth);
                   if (enterpriseSession != null)
                   {//Create and store useful objects for the session.
                        IInfoStore iStore = (IInfoStore)enterpriseSession.getService("InfoStore");
                        ReportEngine reportEngine = (ReportEngine)enterpriseSession.getService("WebiReportEngine");
                        IInfoObject infoView = null;
                        String str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS WHERE (SI_KIND = '"+CeKind.WEBI+"' OR SI_KIND='FullClient') " +
                        "AND SI_INSTANCE = 'false' AND SI_NAME='Structure Test_001_Java' ORDER BY SI_NAME ASC ";
                        //String str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS ORDER BY SI_NAME ASC ";
                        IInfoObjects objInfoObjectsWIDs = (IInfoObjects) iStore.query(str);
                        System.out.println(objInfoObjectsWIDs.size());
                        IInfoObject objInfoObjectWID = (IInfoObject) objInfoObjectsWIDs.get(0);
                        DocumentInstance doc = reportEngine.openDocument(objInfoObjectWID.getID());
                        DataProviders dps = doc.getDataProviders();
    //                     Retrieve the 1st data provider
                        DataProvider dp = dps.getItem(0);
    //                     Retrieve the universe objects
                        DataSource ds = dp.getDataSource ();
                        Query q = dp.getQuery();
                        Recordset rs = dp.getResult(0);
    //                     0: assume query has one flow
                        rs.first();
    //                     Print the column types. They can be Integer, String,
    //                     or Date.
                        for (int i = 0; i < rs.getColumnCount(); i++) {
                        Class c = rs.getColumnType(i);
                        StringBuffer sbt = new StringBuffer();
                        if ( c.equals(Integer.class) )
                        sbt.append("Integer");
                        if ( c.equals(String.class) )
                        sbt.append("String");
                        if ( c.equals(Date.class) )
                        sbt.append("Date");
                        sbt.append(";");
                        System.out.println(sbt.toString());
                        System.out.println(rs.getColumnCount());
                        while (!rs.isLast()) {
    //                          column names
                             StringBuffer sbn = new StringBuffer();
                             StringBuffer sbd = new StringBuffer();
                             for (int j = 0; j < rs.getColumnCount(); j++) {
                             sbn.append( rs.getColumnName(j).toString() );
                             sbn.append(";");
                             System.out.println("sbn "+sbn.toString());
    //                          data
                             for (int k= 0; k< rs.getColumnCount(); k++) {
                             sbd.append( rs.getCellObject(k).toString() );
                             sbd.append(";");
                             entire.add(rs.getCellObject(k).toString());
                             System.out.println("sbd "+sbd.toString());
                             rs.next();
                        System.out.println(entire.size());
                        for(int i=0;i<entire.size();i++){
                             country.add(entire.get(i));
                             i++;
                             System.out.println("entireList "+entire.get(i));
                             resort.add(entire.get(i));
                        DataSourceObject city = ds.getClasses().getChildByName("Country");
                        DataSourceObject resorts = ds.getClasses().getChildAt(1);
                        dp.runQuery();
                        ReportContainer report = doc.createReport("Resort");
                        PageHeaderFooter header = report.getPageHeader();
                        FreeCell headerCell = header.createFreeCell("Resort Report");
                        PageHeaderFooter footer = report.getPageFooter();
                        FreeCell footerCell = footer.createFreeCell("Report Ends");
                        ReportBody body =  report.createReportBody();
                        for(int k=0;k<resort.size();k++){
                        FreeCell res=body.createFreeCell(resort.get(k));
                        res.getAttachTo();
                        res.setHeight(15d);
                        res.setWidth(30d);
                        Color c = new Color(255,255,255);
                        Color c1 = new Color(255,0,0);
                        FontImpl fnt = (FontImpl)res.getFont();
                        fnt.getDecoration().setTextColor(c1);
                        res.setFont(fnt);
                        //res.deleteAttachment();
                        //res.setAttachTo(body,VAnchorType.BOTTOM,HAnchorType.NONE);
                        doc.applyFormat();
                        doc.refresh();
                        final String l_docToken = doc.getStorageToken();
                        final DocumentInstance l_docToSave = reportEngine.getDocumentFromStorageToken(l_docToken);
                        doc.saveAs("mor31",835,null,null);
                        doc.closeDocument();
                        str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS WHERE (SI_KIND = '"+CeKind.WEBI+"' OR SI_KIND='FullClient') " +
                        "AND SI_INSTANCE = 'false' AND SI_NAME='mor31' ORDER BY SI_NAME ASC ";
                        //String str = "SELECT SI_ID, SI_NAME, SI_PARENTID FROM CI_INFOOBJECTS ORDER BY SI_NAME ASC ";
                        objInfoObjectsWIDs = (IInfoObjects) iStore.query(str);
                        System.out.println(objInfoObjectsWIDs.size());
                        objInfoObjectWID = (IInfoObject) objInfoObjectsWIDs.get(0);
                        DocumentInstance doc1 = reportEngine.openDocument(objInfoObjectWID.getID());
                        String token = doc1.getStorageToken();
                        DocumentInstance doc2 = reportEngine.getDocumentFromStorageToken(token);
                        doc2.saveAs("123123", 835, null, null);
                   //     doc.refresh();
                        //doc.save();
                   enterpriseSession.logoff();
              catch(Exception e)
                   e.printStackTrace();

    duplicate post:
    Sample report using JAVA SDK

Maybe you are looking for

  • My phone stopped working and i can't turn it on. I want to know if it can be replaced for free because it's still in warranty!

    Hi, I was wondering what is the warranty policy. A year ago I was using Iphnone 4 s and the camera stopped working and the carier gave me a new. I couple of month ago I bought Iphone 5 and yesterday it just stopped working. My question is want ca I d

  • Why do my photos duplicate in a Collection when I export them

    I exported some of the photos in my collection and now I see the same picture twice when I click on the collection. I you control-click the photos in Lightroom and select Show in Finder in the por-up menu, it will show the same file for both the pict

  • Random loss of songs

    I went to play some music from my iPod Touch today, only to discover that the majority of my library was gone. Poof! I had recently downloaded quite a bit, and all of my very recent downloads appear, but none of the older purchases and none of the mu

  • LMS 4.2 Fault Monotor

    Hi I useLMS 4.2, In fault Monitor I have the folowing messages : Event_Description StateNotNormal Device IP 10.92.8.142 Device Type Switches and Hubs Fault Last Updated At 17-Nov-2013 12:36:25 Component PWR-I@/2058 [Sw2, PS1 Faulty, RPS NotExist] Com

  • ISE Hot Spot Certificate Error

    We've just setup an ISE server (Version 1.3.0.876) and have configured a Hot Spot portal for guest users. Everything about the portal works just fine, however! The issue we are running into is we have installed a public cert signed by a public CA (St