简体   繁体   English

将对象存储在ArrayList中而不是Array中

[英]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. 我目前有一个程序,可以将对象存储在需要存储在ArrayList中的ArrayList

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. 这是行不通的,我已经尝试过变种,但是我真的不知道该怎么做。

Instead of 代替

Letter x = new Letter.charAt(i); 

you need 你需要

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

in your 2nd code snippet 在您的第二个代码段中

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. 在charAt之前,但其他一切似乎都是正确的。

Try to think of the object > string > charAt sequence carefully when you reread your code. 重读代码时,请仔细考虑对象>字符串> charAt序列。 Ask yourself when you read over your code: "what is it exactly about the object that I want to reference/change?" 阅读代码时问自己:“我要引用/更改的对象到底是什么?”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM