(37) Arraylist with objects in Java
Overview of Using ArrayLists with Objects
This video focuses on creating and using ArrayLists with custom objects, specifically a class named
Hero.
Creating the Hero Class
Class Definition:
HeroAttributes:
name: the hero's namepowerLevel: the hero's power levelhp: current hit pointsmaxHp: maximum hit points
Constructors:
Default Constructor: Initializes attributes with default values.
Three-Argument Constructor: Initializes the attributes with provided values using
this.to distinguish the class variables.
toString Method:
Overrides the default
toString()method to return formatted string representation of the hero's attributes, including hit points as a fraction.
Creating an ArrayList of Hero Objects
ArrayList Definition:
Use
ArrayList<Hero> heroes = new ArrayList<>();to create an ArrayList to hold Hero objects.Import
java.util.ArrayList.
Creating Hero Objects:
Example:
Hero h1 = new Hero("Fred", 300, 100);Create multiple Hero instances with varying attributes.
Adding Heroes to ArrayList:
Use
heroes.add(h1);to add objects to the ArrayList.
Manipulating ArrayLists
Printing Heroes:
Use a
forloop to iterate through the ArrayList and calltoString()on each Hero to print their details.
Removing Heroes:
Use
heroes.remove(object)orheroes.remove(index)to remove specific objects from the ArrayList.Example:
heroes.remove(h3);orheroes.remove(2);to remove Hero "Doug".
User Input for Removal:
Scanner Usage: Import and use
Scannerto get user input for which Hero to remove.Example: Check if user input matches each Hero's name and remove if found.
Modifying Heroes in ArrayList
Access and modify an existing Hero's properties using
heroes.get(index).property = newValue;Example:
heroes.get(4).powerLevel = 500;to update Bob's power level.
Conclusion
This video provides a foundational understanding of creating and manipulating ArrayLists containing objects, highlighting the importance of class constructors, methods, and how to access and modify object attributes within the ArrayList.