-
write a hero object class
package cn.jse.t1;
public , class hero {
public string Name;
public float hp;
public int damage;
public hero () {}
//Add a constructor to initialize name
public hero (String name) {
this . Name=name;
}
//Override a ToString method
public string toString () {
return name;
}
}
Write a test class
Package cn.jse.t1;
Public class testcollection {
Public Static void Main (string[] args) {
Limitations of arrays
Hero hero[] = new hero[10];
Analysis: Declared an array of length 10, if not finished is a waste of memory, more than 10 and not fit
Hero[0] = new Hero ("ADC");
hero[11]= new Hero ("Mid"); There's more than 10 here and there will be an error.
}
}
in order to solve this embarrassing situation, we can use the container class ArrayList, We add some code inside the test class.
Package cn.jse.t1;
import java.util.ArrayList;
Public class testcollection {
Public Static void Main (string[] args) {
...
In order to solve the limitation of array, the concept of container class is introduced.
ArrayList heros=new ArrayList();
heros . Add (new Hero ("single"));
Output the capacity of the current container
System. out. println (Heros.size ());
heros . Add (new Hero ("aux"));
System. out. println (Heros.size ());
The result is that the capacity of the container increases with the increase of the object, and the boundary problem of the array is not considered.
}
}
We can look at the output of the console:
1
2
we can take a look . Common methods of ArrayList:
How to use: We also add new code (add,contains) to the test class
Package cn.jse.t1;
import java.util.ArrayList;
Public class testcollection {
Public Static void Main (string[] args) {
...
Next we can look at the common methods of ArrayList
arraylistNew arraylist
Put five objects into a ArrayList
for (int i=0;i<5;i++) {
Heros2.add (new Hero ("Hero" + i));
}
System. out. println (heros);
Add an object at the specified position such as in Subscript 3 position add a superhero
Hero superhero = new Hero ("Super Hero");
Heros2.add (3, superhero);
Outputs all the hero in the array
System. out. println (Heros2.tostring ());
Determine whether an object is in a container by means of contains
System. out. println ("Then this Hero6 is not here?") The answer is: "+heros2.contains (new Hero (" Hero6 "));
System. out. println ("then this superhero is not here?") The answer is: "+heros2.contains (superhero));
}
}
Console output:
[Middle order, auxiliary]// This is because we have added 2 hero
[Hero 0, Hero 1, Hero 2, Super hero, Hero 3, Hero 4]
so this Hero6 's not here? The answer is: false
so this superhero is not here? The answer is: true
Other methods are not listed, interested students can look at the relevant knowledge points