用不可变得特性定义一个老师类

 

package com.yelang;

public class Teacher {

    private String name;
    private int age;
    private String sex;

    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;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Teacher() {
        super();
    }

    public Teacher(String name, int age, String sex) {
        super();
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Teacher [name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        result = prime * result + ((sex == null) ? 0 : sex.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Teacher other = (Teacher) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        if (sex == null) {
            if (other.sex != null)
                return false;
        } else if (!sex.equals(other.sex))
            return false;
        return true;
    }

    public int findUCount(String source) {
        int result = 0;
        char[] charArray = source.toCharArray();
        char searchChar = 'u';
        for (char item : charArray) {
            if (item == searchChar) {
                result++;
            }
        }
        return result;
    }
    
    public String findMiddle(String source) {
        String [] str = source.split(" ");
        int index = str.length % 2 == 0 ? str.length / 2 -1 : str.length / 2;
        System.out.println(index);
        return str[index];
    }
    
    public static void main(String[] args) {
        Teacher t = new Teacher("张三", 36, "男");
        Teacher t1 = new Teacher("张三", 36, "男");
        System.out.println(t);
        System.out.println(t.equals(t1));
        System.out.println(t.findUCount("good good study day day up"));
        System.out.println(t.findMiddle("all roads lead to roma"));
    }
}