Can we pass List to object in Java?

Part 4

  • You can add objects to a list
  • You can go through objects in a list

The type parameter used in creating a list defines the type of the variables that are added to the list. For instance, ArrayList includes strings, ArrayList integers, and ArrayList floating point numbers

In the example below we first add strings to a list, after which the strings in the list are printed one by one.

ArrayList names = new ArrayList[]; // string can first be stored in a variable String name = "Betty Jennings"; // then add it to the list names.add[name]; // strings can also be directly added to the list: names.add["Betty Snyder"]; names.add["Frances Spence"]; names.add["Kay McNulty"]; names.add["Marlyn Wescoff"]; names.add["Ruth Lichterman"]; // several different repeat statements can be // used to go through the list elements // 1. while loop int index = 0; while [index

Chủ Đề