#ArrayList

1 messages · Page 1 of 1 (latest)

naive berry
#

can someone help me why isnt my array list working

foggy valleyBOT
#

<@&987246883653156906> please have a look, thanks.

bright trail
naive berry
#

so i need to loop it with charAt?

lyric pilot
#

A proper answer should really start with "what are you trying to achieve", because there are a number of curiosities in your code (in addition to the errors).

  1. You can't use array-indexed access to List implementations - ArrayList is not an array, it is a List with a performance profile similar to an array.
  2. You can't use array-indexed access on a Student. It's unclear what your intention is here.
  3. Your list has three elements, but your loop only visits 2 of them (index 0 and index 1) so even if you were using graduatedStudents.get(i) to extract the students, you'd neve see lee.

You probably want something more like.

List<Student> students = new ArrayList<>();
students.add(stani);
students.add(martin);
students.add(lee);

for (Student student : students) { // this is an enhanced-for loop that will visit each student in the list
   // but it's unclear what you want to loop over for student... I'll guess it's name...
   String name = student.getName();
   for (int c = 0; c < name.length(); c++) {
      System.out.println(name.charAt(c)); // String.charAt(int) gets a single char from the String.
   }
}

You'll notice I used List<Student> instead of ArrayList<Student>. List is the interface that all list implementation use.

If you don't need to update the list, this would let you write the list setup much more concisely (though there are tricks for ArrayLists too)...

List<Student> students = List.of(stani, martin, lee);

List.of(...) gives you an unmodifiable list - and for reasons you'll learn later, we often prefer this.