软件设计18

发布时间 2023-12-28 11:37:09作者: 那年晚风可期

[实验任务一]JAVAC++常见数据结构迭代器的使用

1305班共44名同学,每名同学都有姓名,学号和年龄等属性,分别使用JAVA内置迭代器和C++中标准模板库(STL)实现对同学信息的遍历,要求按照学号从小到大和从大到小两种次序输出学生信息。

实验要求:

1. 搜集并掌握JAVAC++中常见的数据结构和迭代器的使用方法,例如,vector, list, mapset等;

2. 提交源代码;

package text01;

 

public class Gj19Client {

    public static void main(String[] args) {

        Gj19JavaIterator gj19JavaIterator= new Gj19JavaIterator();

        gj19JavaIterator.display();

    }

}

package text01;

 

import java.util.ArrayList;

import java.util.Collection;

import java.util.Collections;

import java.util.Iterator;

import java.util.List;

 

public class Gj19JavaIterator {

    List<Gj19Student> slist=null;

    public Gj19JavaIterator(){

        Gj19Student[] stu=new Gj19Student[5];

        slist=new ArrayList<Gj19Student>();

        stu[0]=new Gj19Student("张大", 32);

        stu[1]=new Gj19Student("陈二", 25);

        stu[2]=new Gj19Student("王五", 21);

        stu[3]=new Gj19Student("刘六", 38);

        stu[4]=new Gj19Student("王八", 26);

        for(int i=0;i<5;i++){

            slist.add(stu[i]);

        }

    }

    public void display(){

        Iterator<Gj19Student> t=slist.iterator();

        System.out.println("遍历获得的原始数据:");

        while(t.hasNext()){

            Gj19Student student=t.next();

            System.out.println("姓名:"+student.getName()+"今年"+student.getAge()+"");

        }

        Collections.sort(slist);

        Iterator<Gj19Student> it=slist.iterator();

        System.out.println("========================================");

        System.out.println("按年龄从大到小排序:");

        while(it.hasNext()){

            Gj19Student student=it.next();

            System.out.println("姓名:"+student.getName()+"今年"+student.getAge()+"");

        }

    }

 

}

package text01;

 

public class Gj19Student implements Comparable<Gj19Student>{

    private String name;

    private int age;

    public Gj19Student(String name, int age) {

        super();

        this.name = name;

        this.age = age;

    }

    public int compareTo(Gj19Student stu){

        if(this.age > stu.age){

            return -1;

        }else if(this.age < stu.age){

            return 1;

        }

        return 0;

    }

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

}

3. 注意编程规范。