Collection Framework (collection store student objects and traverse)

Source: Internet
Author: User

Create Student class First

Package cn.itcast_04;


public class Student {

private String name;

private int age;


Public Student () {

Super ();

}


Public Student (String name, int.) {

Super ();

THIS.name = name;

This.age = age;

}


Public String GetName () {

return name;

}


public void SetName (String name) {

THIS.name = name;

}


public int getage () {

return age;

}


public void Setage (int.) {

This.age = age;

}


}



To create the collection class again


Package cn.itcast_04;


Import java.util.ArrayList;

Import java.util.Collection;

Import Java.util.Iterator;


/*

* Requirements: Store custom objects and traverse student (Name,age)

*

Analysis

* A: Create student class

* B: Create a Collection Object

* C: Create student Objects

* D: Add student objects to the collection object

* E: Traversing the collection

*/

public class CollectionTest2 {

public static void Main (string[] args) {

To create a collection object

Collection C = new ArrayList ();


Create Student objects

Student S1 = new Student ("Marten Cicada", 25);

Student s2 = new Student ("Little Joe", 16);

Student s3 = new Student ("huangyueying", 20);

Student S4 = new Student ();

S4.setname ("Big Joe");

S4.setage (26);


Add a Student object to the collection object

C.add (S1);

C.add (S2);

C.add (S3);

C.add (S4);

C.add (New Student ("Sun Shangxiang",)); Anonymous Objects


Iterating through the collection

Iterator it = C.iterator ();

while (It.hasnext ()) {

Student s = (Student) it.next ();

System.out.println (S.getname () + "---" + s.getage ());

}

}

}


Or a comparative basis, I hope to help you!

This article from "GD" blog, reproduced please contact the author!

Collection Framework (collection store student objects and traverse)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.