欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

算法之线性查找法

程序员文章站 2022-07-12 11:30:35
...

查找数组中的指定元素

实现:

    /**
     * 线性查找法
     */
    public static<T> int line(T[] lines,T value){
        for(int i=0;i<lines.length;i++)
            if(lines[i].equals(value))
                return i;
        return -1;
    }

实体类测试:

public class Student {

    private String studentCode;

    public Student(String studentCode){
        this.studentCode = studentCode;
    }

    @Override
    public boolean equals(Object obj){
        if(this == obj)
            return true;

        if(obj == null)
            return false;

        if(this.getClass() != obj.getClass())
            return false;

        Student another = (Student)obj;
        return this.studentCode.equals(another.studentCode);
    }

    public static void main(String[] args) {
        Integer[] lines = {12,34,32,234};
        System.out.println(LineDemo01.line(lines,89));

        Student[] students ={ new Student("12"),new Student("23")
        ,new Student("34")};
        Student student = new Student("23");
        System.out.println(LineDemo01.line(students,student));
    }