1

I am trying to load some images into an array for an applet and I know there has to be a better way to do this?

public class Images extends Applet
{
    Image card[]=new Image[45];
    public void init()
    {
        img[0]= getImage( getDocumentBase(),"pics/1.gif");
        img[1]= getImage( getDocumentBase(),"pics/2.gif");
.....
3
  • 2
    Best thing to do is probably to have some kind of configuration file which lists the images to be loaded and use for-loop to load each one based on the needs of the configuration Commented Jun 30, 2014 at 5:46
  • I should have specified that the image names are not all the same - in case that matters Commented Jun 30, 2014 at 5:46
  • Do you want to improve performance? Try to use lazy load strategy. Commented Jun 30, 2014 at 5:48

1 Answer 1

4

Even if the filenames aren't predictable based on number, you could still have a collection of them. For example:

// Common prefix removed for brevity
private static final String[] IMAGE_FILES = {
    "img1.gif", "happy.gif", "sad.gif" /* etc */
};

Then:

Image[] images = new Image[IMAGE_FILES.length];
for (int i = 0; i < images.length; i++) {
    images[i] = getImage(getDocumentBase(), "pics/" + IMAGE_FILES[i]);
}

(There may well be a nicer way of transforming one array into another using a lambda in Java 8 - I haven't checked.)

It's not clear to me that an Images class is a good idea though - it doesn't really sound like something you'd typically create an instance of. I'd also strongly recommend using private fields.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.