编程语言
首页 > 编程语言> > java笔试题(七)

java笔试题(七)

作者:互联网

import java.util.ArrayList;
import java.util.List;

public class Javatest91 {
    /**
     * 枚举、泛型
     * 练习1:list1=[A,B,C],list2=[B,C,A],对比两个列表,内容相同返回ture,不同返回false。
     * 要求定义一个泛型方法实现(解决类型侵入的问题)
     * 说明:A可以任意类型的对象,
     * //学生类
     * class Stu{
     *     String id;
     *     String name;
     *     int age;
     *
     *     public Stu(String id, String name, int age) {
     *         this.id = id;
     *         this.name = name;
     *         this.age = age;
     *     }
     *
     *     public String getId() {
     *         return id;
     *     }
     *
     *     public void setId(String id) {
     *         this.id = id;
     *     }
     *
     *     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;
     *     }
     *
     *     @Override
     *     public String toString() {
     *         return "Stu{" +
     *                 "id='" + id + '\'' +
     *                 ", name='" + name + '\'' +
     *                 ", age=" + age +
     *                 '}';
     *     }
     */
    public static void main(String[] args) {
        //创建集合
        List<Stu> list1 = new ArrayList<>();
        list1.add(new Stu("001","Jack",16));
        list1.add(new Stu("002","Make",17));
        List<Stu> list2 = new ArrayList<>();
        list2.add(new Stu("002","Make",17));
        list2.add(new Stu("001","Jack",16));
        boolean flag = compare(list1,list2);
        System.out.println(flag);


    }
    //比较list1和list2的内容
    public static boolean compare(List<Stu> list1,List<Stu> list2) {
        //1、比较元素个数是否相同
        if (list1.size() != list2.size()) {
            return false;
        }
        //2、比较内容
        for (int i = 0; i < list1.size(); i++) {
            Stu stu1 = list1.get(i);
            boolean flag = false;
            for (int j = 0; j < list2.size(); j++) {
                Stu stu2 = list2.get(j);
                boolean compareResult = compareStu(stu1, stu2);
                if (compareResult) {
                    //比较内容相同,flag置为true
                    flag = true;
                    break;
                }
            }
            //遍历结束,无相同内容,return false
            if (!flag) {
                return false;
            }
        }
        return true;
    }
    //比较两个对象内容是否一致
    private static boolean compareStu(Stu stu1, Stu stu2) {
        if(stu1.id == stu2.id && stu1.name == stu2.name && stu1.age == stu2.age){
            return true;
        }
        return false;
    }
}

 

标签:java,name,age,笔试,id,Stu,return,public
来源: https://www.cnblogs.com/yixiaobaitest/p/16120943.html