I.A. Washburn
I.A. Washburn

Reputation: 39

Storing objects in ArrayList instead of Array

I currently have a program that stores objects in an array that I need to store in an ArrayList instead.

This is how the objects were originally stored.

private String phrase = "Once upon a time";
private Letter[] letter_array = new Letter[16];

for (int i = 0; i < phrase.length(); i++) {
  letter_array[i] = new Letter(phrase.charAt(i));
  }

So now, I'm trying to use something like this instead.

private String phrase = "Once upon a time";
ArrayList<Letter> aToZ = new ArrayList<Letter>();

for (int i = 0; i < phrase.length(); i++) {
  Letter x = new Letter.charAt(i);
  aToZ.add(x);
  }

Some of the code has been omitted, but these are the pertinent parts.

This doesn't work and I've tried variations, but I just really don't know how to do this.

Upvotes: 0

Views: 100

Answers (2)

Robert Plant
Robert Plant

Reputation: 67

Letter x = new Letter(phrase.charAt(i));

You almost had it! You need to include the "phrase." before charAt, but everything else seems to be correct.

Try to think of the object > string > charAt sequence carefully when you reread your code. Ask yourself when you read over your code: "what is it exactly about the object that I want to reference/change?"

Upvotes: 1

Faraz
Faraz

Reputation: 6285

Instead of

Letter x = new Letter.charAt(i); 

you need

Letter x = new Letter(phrase.charAt(i));

in your 2nd code snippet

Upvotes: 4

Related Questions