ArrayList of object
Understand the following program--------------------------------------
Main.java
------------------------------------
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
List<Team> l=new ArrayList<Team>();
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("Enter the team name");
String name=sc.next();
System.out.println("Enter the team id");
int id=sc.nextInt();
l.add(new Team(name,id));
}
PrintTheList p=new PrintTheList();
p.Print(l);
}
}
Main.java
------------------------------------
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
List<Team> l=new ArrayList<Team>();
int n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println("Enter the team name");
String name=sc.next();
System.out.println("Enter the team id");
int id=sc.nextInt();
l.add(new Team(name,id));
}
PrintTheList p=new PrintTheList();
p.Print(l);
}
}
Team.java
------------------------------------------
public class Team {
String name;
int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Team(String name, int id) {
super();
this.name = name;
this.id = id;
}
@Override
public String toString() {
return "Team [name=" + name + ", id=" + id + "]";
}
}
PrintTheList.java
-------------------------------------------------------
package Practice1_ARrayListOfObject;
import java.util.List;
public class PrintTheList {
public void Print(List<Team> l)
{
for(Team t:l)
{
System.out.println(t);
//or
//System.out.println("id is "+t.getId()+" Name is "+t.getName());
}
}
}
Explanations:-
In the above program i created the array list<Team> that means the array list stores the object of Team class which have two attributes such as name and id.
Then i call a function from another class i.e. PrintTheList and pass the array list to that class.In that class i printed all the values.
In the line for(Team t:l) i have used for each loop.As i have stored all the element in arraylist as objects of class Team so its madetory while using forEach loop to store it in a same object reference i.e. Team t.
System.out.println(t);
While i print the above line that means i am printing the team object.As i am printing the team object the toString() of Team class will be called which we have overriden in Team class
@Override
public String toString() {
return "Team [name=" + name + ", id=" + id + "]";
}
and print accordingly.
Otherwise we can write-
System.out.println("id is "+t.getId()+" Name is "+t.getName());
Here we are using get method (getter setter methods in Team class) to get the name and id of the object.
Comments
Post a Comment