Good programming practices:   creating Iterator objects

Hi,
This is a question about Good programming practices for creating Iterator objects of ArrayList objects. The following line of code works fine in my program (as ridiculous as it may sound):
        Iterator cheesesIterator = cheeses.iterator();but I was wondering whether Java is automatically inserting the <Type> and new code to make:
        Iterator<String> cheesesIterator = new cheeses.iterator();and therefore whether it is good practice to use these everytime? Thank you. ("full" code shown below:)
import java.util.ArrayList;
import java.util.Iterator;
public class DemonstrateIterator
    private ArrayList<String>  cheeses;
     * constructor:
    public DemonstrateIterator()
        cheeses = new ArrayList<String>();
        cheeses.add("Emmentaler");
        cheeses.add("Cheddar");
        cheeses.add("Stilton");
        cheeses.add("Brie");
        cheeses.add("Roquefort");
    public void listCheeses()
         //make an iterator object of the ArrayList object
        Iterator cheesesIterator = cheeses.iterator();
        while (cheesesIterator.hasNext()) {
            System.out.println(cheesesIterator.next());
        /** Exploring the toString and Super functions. **/       
        System.out.println("\na toString call to Super returns: " +
                                          super.toString() + "\n");
}

AJ-Phil wrote:
Hi,
This is a question about Good programming practices for creating Iterator objects of ArrayList objects. The following line of code works fine in my program (as ridiculous as it may sound):
        Iterator cheesesIterator = cheeses.iterator();but I was wondering whether Java is automatically inserting the <Type> and new code to make:
        Iterator<String> cheesesIterator = new cheeses.iterator();and therefore whether it is good practice to use these everytime? TFirst, new chesses.iterator() won't compile.
iterator() is just a method that returns an iterator. It constructs an instance of a private or nested class that implements iterator, and returns a reference to it.
As for the <T>, when you declare List<String>, that parameterizes that list with type String. The iterator() method returns Iterator<T>. You can look at the source code for yourself. It's in src.zip that came with your JDK download.
Separate from that is your declaration of that variable as type Iterator, rather than Iterator<String>. Regardless of what you declare on the LHS, the iterator() method returns Iterator<T>. Your bare Iterator is essentially Iterator<Object> or Iterator<? extends Object> (not sure which, or what the difference is), which is assignment compatible with Iterator<T>. If you had declared it Iterator<String>, you wouldn't have to cast after calling next().
Edited by: jverd on Nov 23, 2008 11:33 AM

Similar Messages

  • Good programming practice - Abstract class

    Hi all,
    I have been trying to help another soul in this forum, and came to the conclusion that I don't know good
    programming practice when it comes to abstract classes.
    Is this correct?
    You CAN implement methods in an abstract class, but it's not recommended.
    I have NEVER done this...when is there possibly a need to?
    Regards.
    / k

    Yes, absolutely, you can implement methods in an abstract class. Any method that all subclasses will perform in the same way can be implemented in the abstract base class. If subclasses perform similiar functions depending on their type you declare those as abstract in the base class. Here is a contrived example that I have seen on job interviews.
    Suppose your developing an application that draws on a panel. We want to provide some canned shapes such as a circle, a square and a triangle. We want to be able to draw the shape set or get its color and calculate its area.
    Let's define an abstract base class Shape
    public abstract class Shape{
        private Color myColor;
       //  since color has nothing to do with what kind of shape we're working with, create concrete implementation
       public Color getColor(){
            return myColor;
    public void setColor(Color newColor){
       myColor = newColor;
    // however, drawing the shape and calculation its area are depending on the actual shape.
    public abstract void draw();
    public abstract double getArea();
    // so then Square would be something like
    public class Square extends Shape{
       public double get Area()
          return sideLength * sideLength  // assumes somehow we know sideLength
    public void draw(){
                  // concrete implementation
    }we can do the same things for Circle class and Triangle class.
    And, if you think about it you'll notice that we could have made a Rectangle class and then Square would be a subclass of Rectangle where both dimensions are equal.
    I hope that somewhat strained example helps answer your question.
    DB

  • Do IOS app developers follow any good program practices?

    I've had my iPad (original) a little over two years now, and I can say without a doubt, it is the most unstable platform I've used in nearly 30 years of using computers.  Most apps crash routinely, usually while at least one other app is running in the background.  Unloading the crashed app from memory and reopening uually works, but is a huge nuisance (and reason enough to me why iPads are not business-ready, except for specific task applications requiring mobility).  As one trained in both software and systems engineering, with 20 years IT experience mostly in engineering, I have to conclude that IOS app developers use "code and fix" development, with little testing before release.  Of course, in theory it could be that IOS itself isn't well designed to handle multitasking and doesn't provide adequate process isolation.  Either way, it makes for a frustrating experience as a user.
    Has anyone else had similar issues?  Thoughts on why?

    The original iPad does poorly with multiple apps open, the memory is just too small at 256 MB.  The processor is very slow compared to those in the current generation iPads.  And then couple that with developers who are for the most part independent of Apple and merely submit there products to Apple and you get a totally unpoliced set of apps.  Some are true professionals and follow very good programming practices, one that comes to mind is the GoodReader PDF reader.  Very stable and very powerfully built.  then you get into the gamers and Is is almost like they never heard of writing effecient, compact code.
    The issue I see is a tightly controled operating system, with app developers handed a set of specs under which to code, but no real controls other than does the app run and is it free of malicious code.
    Just some thoughts.

  • Examples for good programming practice with multiple DAQmx tasks

    I'm writing a program to continuously log data from 8 counters, 8 encoders, and 8 voltages. The proof of concept VI with a single counter was simple and elegant, but scaling up to all signals resulted in a wiring mess. I've been working through the Labview Core courses, and am currently on Core 3. I still haven't come across a discussion on how to work with multiple DAQmx tasks without making a mess of the block diagram. Can anyone point me in the right direction?
    Also, say I have a state machine that has a configure, idle, and logging states. I need to set the initial values of the encoders during configuration, and keep up with their changes while in the idle state so I have appropriate starting values when entering the logging state. Can anyone point to an example that shows how this might be accomplished?
    Thanks

    I'm very familiar with AE's/Functional Globals - but I have struggled in the past with handling multiple DAQmx tasks - particularly when you're using multiple devices and using different types of measurements which require seperate tasks/handling (e.g. such as thermocouples which require extra compensation).
    I'm not even sure I know whare the requirements are for needing multiple tasks - I know you can need multiple tasks for a single device if the type of measurement is different but can you share an Analogue Input task amongst multiple devices?
    I think in hindsight (and without too much thought now) it looks like a good case for Object Oriented LabVIEW - with a base DAQmx class (initialise, configure, start, acquire, stop, close etc.) and then child classes for each type of measurement (with one task associated with each - and private data unique to that specific class). You then hold an array of objects (one for each task) and iterate through each one with dynamic despatch to get the data.
    I don't know your particular experience level of using LabVIEW (and as such, OO may not be appropriate) - but as a wider discussion of 'best practice' it seems like an appropriate method I would use going forward.
    Certified LabVIEW Architect, Certified TestStand Developer
    NI Days (and A&DF): 2010, 2011, 2013, 2014
    NI Week: 2012, 2014
    Knowledgeable in all things Giant Tetris and WebSockets

  • "Good programming practice" question about writing classes

    I am taking a java class this year and my teacher has taught us to never use global variables in a class (but still private). I find it much easier to explain with a simple example. Say I have a class that looks like this:
    public class Demo
            private int int1, int2;
         public Demo()
              int1 = 1;
              int2 = 2;
         public void demoMethodOne(int int1, int int2)
              //... code using the ints passed to the method
         public void demoMethodTwo()
              //... code directly accessing the private ints of the class
            public int getInt1() { return int1; }
            public int getInt2() { return int2; }
    }My teacher says to ALWAYS use methods of the type demoMethodOne (to pass all of the variables it will use to it) and avoid using the type demoMethodTwo. But in my programming experience, I have found it very repetitive and pointless to use that method in some cases. For example if I call demoMethodOne like this:
    demoMethodOne(demo.getInt1(), demo.getInt2());
    That seems very repetitive but that is how I am told to do it. Should I program that way even if it seems very pointless or is it ok to use "public" variables like in demoMethodTwo. Thanks.

    I think you may have misunderstood your teacher.
    If your object method is doing something with the object's state, then it's perfectly appropriate to modify the object's fields, which embody the state.
    And generally it's good to adopt a functional programming approach, in which there are few side effects. This principle is sort of independent of the previous one.
    The danger is when you treat object fields as global variables (and not as the embodiment of the object's state). In this case the global variable doesn't really represent anything, it's just a place to store data temporarily to avoid designing your methods properly. So for example you'd have two methods, one sets a field and then calls another method, which reads the field; the field doesn't really mean anything to the object as a whole, it's just a lazy way to pass data between the two methods. This is asking for bugs. The correct thing would have been to pass the value as an argument to the second method.
    Also, if you have a method that doesn't really express the behavior or effect the state of an object, but is called just for its return value (like some kind of utility method), then it's pointless and dangerous to make it effect the state of an object.

  • Good programming practices

    I'm writing a straight forward database app with Java to do the logic and GUI. I have a User class and a "create" method to create a new user. In my database, the user table has a bunch of fields (the typical name, address, etc, etc), but only a few are required. I'm trying to figure out the most proper way to do this.
    It would be much easier on the client programmer to pass some sort of hash, but I'd imagine this would generate bad documentation. If I required them to pass 30 parameters, it would get very annoying very quick, but it would generate easy to read api documentation that would play well with IDE's. How would you guys tackle this? Lot's of parameters and good javadocs, or 1 hash and bad generated api documentation.

    cbaechle wrote:
    That's the correlation to the database table. There's a lot of info that can be stored on a user. username, password, email, address, city, state, zip, home phone, cell phone, work phone, etc, etc. It adds up quick and honestly, separating them out will needlessly make it more complicated than need be. I could make an address class I suppose, but for the intention I doubt it would ever be useful.It'll be useful when a single person can have two addresses (e.g., home and office) or when two people live at a single address (data normalization).
    It's the standard way to design a database schema.
    I don't think it's more complicated to have addresses separated out. It's easier to grok because the data is grouped into meaningful bunches. Why would your username be tied to your work phone number?

  • Good programming practice

    There are 2 sets of code which I extracted from a dummy book. The author just want to illustrate 2 ways that we can capture an exception.
    Code set 1_
    import static java.lang.System.out;
    class GoodNightsSleepA {
        public static void main(String args[]) {
            out.print("Excuse me while I nap ");
            out.println("for just five seconds...");
            takeANap();
            out.println("Ah, that was refreshing.");
        static void takeANap() {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                out.println("Hey, who woke me up?");
    Code set 2_
    import static java.lang.System.out;
    class GoodNightsSleepB {
        public static void main(String args[]) {
            out.print("Excuse me while I nap ");
            out.println("for just five seconds...");
            try {
                takeANap();
            } catch (InterruptedException e) {
                out.println("Hey, who woke me up?");
            out.println("Ah, that was refreshing.");
        static void takeANap() throws InterruptedException {
            Thread.sleep(5000);
    }To u guys who are experienced java programmer out there. Which set of code do u think is better coding practice and u'll usually code that way ? I personally would say GoodNightsSleepA is a better practice. Or u guy have some other better suggestion ? Thank you.

    Thank you to everybody who responded to this thread. Can anyone pls point me to a link that talks about proper OOP system analysis and design. I believe I need some foundation on this, otherwise I can't write a proper scalable code. Like some of u has pointed that the GoodNightsSleepB class will be more appropriate coz it provides flexibility to other user who would like to use it as a subclass. I didn't thought of this b4 until u guys have enlighten me.
    To corlettk, I'm totally new to AOP. I just read some of the links from the google search result. I'm still in a very blur stage about AOP. Am I right to assume that we should only code to include basic business requirement functions(primary task) in our class and make use of AOP to do the secondary task(such as data verification/exception capturing) ? Pls correct me if I'm wrong. Thank you in advance, guys.

  • Is this a good programming practice?

    Putting a "throws Exception" in the constructor.
    class Test
    public Test throws Exception {
    }

    I read somewhere that the possibility that something can go wrong in a constructor is one of the convincing arguments for having exceptions in the first place, since there's really no other (reasonable) way to report an error back to the caller. So yes, have a constructor throw an exception (and declare which one(s) it may throw) is a very fine practice as far as I'm concerned.
    I agree that "throws Exception" is poor practice for all methods. Much better to write "throws Exception1, Exception2, Exception47, ExceptionA, YetADifferentExceptionClass" even if it takes a couple of lines.
    Message was edited by:
    OleVV

  • Create a object in form of circle, line, triangle or other shapes

    i am trying to make a program that creates simple objects, its just a hobby. the problem is i am trying to make an object that is only a line(for now). i mean i want to have an object that can be in a shape of anything in any angle. i like to be able to create a straight line from top left corner to bottom right corner, but i do not want to draw it, i want it to be an object like JButton but in different shapes. how ever i cannot do that. i have already wrote a little test program to show every one what i have, it s not my actual code just a sample.
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JButton;
    import javax.swing.JLayeredPane;
    import java.awt.BorderLayout;
    import javax.swing.JLabel;
    import java.awt.Color;
    import javax.swing.event.MouseInputListener;
    import java.awt.event.MouseEvent;
    import javax.swing.JComponent;
    import javax.swing.AbstractButton;
    import java.awt.Graphics;
    import java.awt.Dimension;
    import java.awt.Polygon;
    import java.awt.Graphics2D;
    import java.awt.BasicStroke;
    import java.awt.RenderingHints;
    import java.awt.geom.Area;
    public class FractalTest extends JFrame
         public static final int H=600;
         public static final int W=600;
         public static final Dimension dim = new Dimension(H,W);
         private int[] joinInt = new int[]{BasicStroke.JOIN_MITER,BasicStroke.JOIN_ROUND,BasicStroke.JOIN_BEVEL};
         private int[] capInt = new int[]{BasicStroke.CAP_BUTT,BasicStroke.CAP_ROUND,BasicStroke.CAP_SQUARE};
         public FractalTest(){
              super("Test");
                    //two test lines
              Polygon p = new Polygon();
              p.addPoint(150,150);
              p.addPoint(450,450);
              Polygon s = new Polygon();
              s.addPoint(450,150);
              s.addPoint(150,450);
              setBackground(Color.YELLOW);
              setLayout(new BorderLayout());
                    //status bar at buttom
              JLabel info = new JLabel("info");
                    //creating JPanel holder of lines
              JPanelCanvas test = new JPanelCanvas();
              test.setBackground(Color.BLACK);
              test.setSize(dim);
              test.setLayout(new BorderLayout());
                    //creating lines
              TestComponent t1 = new TestComponent(p,2f,"Polygon P");
              TestComponent t2 = new TestComponent(s,5f,"Polygon S");
                    //setting JLables for status info
              t1.setInfoDisplay(info);
              t2.setInfoDisplay(info);
              test.setInfoDisplay(info);
              test.add(t1,BorderLayout.CENTER);
              test.add(t2,BorderLayout.CENTER);
              add(test,BorderLayout.CENTER);
              add(info,BorderLayout.SOUTH);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              setSize(dim);
              setVisible(true);
              repaint();
         public static void main(String[] args){new FractalTest();}
         private class TestComponent extends AbstractButton implements MouseInputListener
              private float thickness;
              private Polygon polygon;
              private String name=null;
              private JLabel jl=null;
              public TestComponent(Polygon p,float t,String name){
                   super();
                   thickness=t;
                   polygon=p;
                   setContentAreaFilled(false);
                   this.name=name;
                   setSize(FractalTest.dim);
                   setVisible(true);
                   addMouseListener(this);
              public void paint(Graphics g){
                   super.paintComponent(g);
                   Graphics2D g2 = (Graphics2D)g;
                   g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
                   g2.setStroke(new BasicStroke(thickness,capInt[0],joinInt[0]));
                   g2.setPaint(Color.GREEN);
                   g2.drawPolygon(polygon);
              public boolean contains(int x, int y){
                   int Ax=polygon.xpoints[0];
                   int Ay=polygon.ypoints[0];
                   int Bx=polygon.xpoints[1];
                   int By=polygon.ypoints[1];
                   int m=(By-Ay)/(Bx-Ax);
                   int s1=(m<=0)?+1:-1;
                   int s2=(m<=0)?-1:+1;
                   Polygon p = new Polygon();
                   p.addPoint(Ax+1,Ay+(int)(s1*thickness));
                   p.addPoint(Bx+1,By+(int)(s1*thickness));
                   p.addPoint(Bx-1,By+(int)(s2*thickness));
                   p.addPoint(Ax-1,Ay+(int)(s2*thickness));
                   return p.contains(x,y);
              public void setInfoDisplay(JLabel jl){this.jl=jl;}
              public void mouseEntered(MouseEvent e){jl.setText(name);}
              public void mouseExited(MouseEvent e){jl.setText("Polygon");}
              public void mouseDragged(MouseEvent e){}
              public void mouseMoved(MouseEvent e){}
              public void mouseClicked(MouseEvent e){}
              public void mousePressed(MouseEvent e){}
              public void mouseReleased(MouseEvent e){}
         private class JPanelCanvas extends JPanel implements MouseInputListener
              private JLabel jl;
              public JPanelCanvas(){}
              public void setInfoDisplay(JLabel jl){this.jl=jl;}
              public void mouseEntered(MouseEvent e){jl.setText("Canvas");}
              public void mouseExited(MouseEvent e){jl.setText("info");}
              public void mouseDragged(MouseEvent e){}
              public void mouseMoved(MouseEvent e){}
              public void mouseClicked(MouseEvent e){}
              public void mousePressed(MouseEvent e){}
              public void mouseReleased(MouseEvent e){}
    }if u see the code, the problem is each of the lines are covering the hole frame not just the green line, and i have to use the contains() method to limit the function but i do not want to do that. i just want it to be an object with out need of drawing any lines. just creating and object with the background color. so for example a JPanel in circular form that is only a circle no extra area around it.
    if u run the application and run it u will see the JPanel behind the green lines is not accessible by the mouse, the status JLabel shows the name of object can be reached by mouse at the moment and canvas(JPanel) will never be invoked. if the mouse is still on line objects the status name will stay on Polygon and it never changes to canvas.
    thanks everyone in advance

    Hi,
    try searching [www.java2s.com].plenty of sample programs are available.I have a faint memory of seeing a code that loads image files in desired placehoders like polygons n stuff. I guess you could replace the image component by some other component. Hope this helps

  • Any usefull examples of good coding practice in large programs

    Hi, ive been writing code for about 10 years now. Know a good bit about labview now lmao! But want to get to know good code practices e.g. in creating large programs, code templates, avoiding race conditions, use of multiple loops and to be able to write code for clients as a contractor. Any one help me??
    Stu
    Solved!
    Go to Solution.

    Check out thelargeapp community and this KB article
    Message Edited by Jeff Bohrer on 06-14-2010 04:49 PM
    Jeff

  • When I try to open an embedded PDF file I get an error "The program used to create this object is AcroExch.exe.

    When I try to open an embedded PDF file (Word doc) I get an error "The program used to create this object is AcroExch.exe. That program is either not installed on your computer, or is corrupt..."  I've tried  about everything from unchecking
    protected mode at startup to removing & reinstalling Adobe.  Nothing seems to fix this issue.  Any other ideas?
    This is happening on Adobe reader 9, 10 & 11 with MS Word 2010 & 2013.  I've uninstalled, cleaned & reinstalled Reader 9, 10 & 11, as well as Acrobat 10 Pro & 11 Standard.  Removed "Protected mode at startup, and changed
    the default program for viewing from reader to Acrobat.  This will not go away.  It is affecting production at our company.

    " Help > Troubleshooting Information > Profile Directory: Open Containing Folder" . i can't find open containing folder in profile directory. it does give me the option to open the places.sqlite file using graphic converter. when i try that, graphic converter gives me a window saying that it can't be opened because it is corrupted or is not a file type supported by graphic converter.
    i appreciate your help with a workaround to get the old bookmarks. that works. however, the problem has morphed from that concern to why adobe reader [the default app.] won't open firefox .sqlite files. is the problem in adobe reader or firefox? also, how can i tell if the places.sqlite file is corrupt?
    i'm getting in over my head here and do appreciate your help.

  • Getting "program used to creat ethis object is AcroExch"

    Getting "program used to creat ethis object is AcroExch. That program is not installed on your computer." when trying to open PDFs embedded in Word.  Some work and some give me the error message above.
    I am on Acrobat Standard 10.1.7 and Word 2007, on Windows 7.
    Anyone have any fixes that might resolve this issue? 

    There is a comment in http://community.spiceworks.com/topic/119912-adobe-10-update-acroexch-error-now-occurring that provides the following information:
    Disabling Protected Mode in Adobe Reader X
    1. Open Adobe Reader X.
    2.From Edit menu select Preferences, Preferences dialog box appears.
    3.Select General category on the list, uncheck or remove tick mark for “Enable protected mode at startup”
    Adobe Reader’s Protected Mode will be turned off.
    Though it is for Reader, I assume it should do the job for Acrobat also.

  • The program used to create this object is acrobat. that program is either not installed or its nor responding?

    The program used to create this object is acrobat. that program is either not installed or its nor responding.
    to edit this object, install Acrobat or ensure that any dialog boxes in Acrobat are closed.
    I have just installed acrobat Pro XI . when inserting an existing adove file as an object this happens. any ideas?

    OLE Embedded Objects seem to have problems with PDF files.   I am not sure if it's OLE or if it's the OLE server (Acrobat/Reader) installed on the machine in this case.  Does this file work on another machine with Acrobat/Reader installed.

  • The program used to create this object is AcroExch. That program is either not installed on your com

    Need help fixing this. I have multiple users who use to be able to embed a pdf in word, but now are unable to. They receive the following:
    The program used to create this object is AcroExch. That program is either not installed on your computer or it is not responding. To edit this object, install AcroExch or ensure that any dialog boxes in AcroExch are closed.

    i found this happened too on my user.
    i'm using :
    1. Microsoft Office 2010 x64
    2. Adobe Acrobat 10 Standard
    I read some articles said that you need to disable the "Enable protection bla bla bla" which is disabled on AA 10 Standard by default.
    At last it's solved after i uninstall the x64 Office 2010 and install the x86 Office 2010.
    I don't know why but its works.
    Hope its works to you too.
    Regards,

  • Create SE61 objects through programs.

    Hi,
    Is there any way to create an SE61 object (Dailog Text) through a program. I have more than 100 objects to be created. Is there any possibilty that I can upload my documentation through a file and create SE61 object for the same?
    Please help me in this regard.
    Regards,
    Kishore.

    Hi
    I recommend you use the API JAXB. Is much simpler.
    here a link: http://www.oracle.com/technetwork/articles/javase/index-140168.html
    here a example: http://download.oracle.com/javaee/5/tutorial/doc/bnbay.html#bnbbc

Maybe you are looking for

  • Phone Shuts Down Repeatedly & Restarts & Won't Charge Since IOS 8 Upgrade

    Jesus please take the wheel. After reading about all the IOS 8 problems in the past few weeks I thought everyone was nuts until two days ago. My iphone 5 has never been mistreated, dropped, slung across a room, or undergone anything approaching tortu

  • Error Message Tag Empty in ESB

    Hi, I am using 10.1.3.4 SOA Suite .I have a FTP adapter in ESB which places my processed file in a FTP location .The problem i am facing is the file which needs to be palced in the FTP location is getting placed perfectly as expected but in the ESB c

  • I sync 2.4 will not load

    iSync for the ical and address book are working fine. the iSync for the phone will not load. and it has a generic Icon. version 2.4. I have: reinstalled the isync. via update. deleted it and reinstalled via update. Tiger disk will not do a isync only

  • Adding voice channels to a trunkgroup

    I have this: controller T1 2/0 framing esf linecode b8zs pri-group timeslots 1-24 description Connection to Switch T1 2 controller T1 2/1 framing esf linecode b8zs pri-group timeslots 1-24 description Conecction to the switch T1 18 It happens that so

  • ABAP Server Proxies - Fault Handling

    Hello, We use ABAP server proxy to create a PO on an R/3 system. This is done in an asynchronous interface. When the function that creates the PO returns an error we raise a fault in the server proxy. However when this occurs the fault is not passed