//工具类
public class ArrayUtil {
//私有化构造方法
//目的:为了不让外界创建他的对象
private ArrayUtil(){}
public static String printArr(int[] arr){
StringBuilder sb = new StringBuilder();
sb.append("[");
for (int i = 0; i < arr.length; i++) {
//i 索引 arr[i] 元素
if (i == arr.length - 1){
sb.append(arr[i]);
}else{
sb.append(arr[i]).append(", ");
}
}
sb.append("]");
//变回字符串
return sb.toString();
}
public static Double getAerage(double[] arr){
double sum = 0;
for (int i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
return sum / arr.length;
}
}
///测试类
public class TestDemo {
public static void main(String[] args) {
//测试工具类中的两个方法是否正确
int[] arr1 = {1,2,3,4,5,6};
String str = ArrayUtil.printArr(arr1);
System.out.println(str);
double[] arr2 = {1.1,2.2,3.3,4.4,5.5,6.6};
Double avg = ArrayUtil.getAerage(arr2);
System.out.println(avg);
}
}
//学生类
public class Student {
private String name;
private int age;
private String gender;
public Student() {
}
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
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 getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
//工具类
public class StudentUtil {
//1.私有化构造方法,不让外界创建她的对象
private StudentUtil(){};
//静态方法 (做事情)
public static int getMaxAgeStudent(ArrayList<Student> list){
//1.定义一个参照物
int max = list.get(0).getAge();//学生对象不能直接赋值给max 要把学生对象的age拿出来
//2.循环遍历集合
for (int i = 1; i < list.size(); i++) {//循环从一开始效率提高
//i 索引 list.get(i) 学生对象 list.get(i).getAge() 学生年龄
/*if (list.get(i).getAge() > max){
max = list.get(i).getAge();
}为了提高代码效率,方法的返回值反复地去用,最好用一个变量接收一下
get方法 getAge方法会重复调用两次*/
int tempAge = list.get(i).getAge();
if (tempAge > max){
max = tempAge;
}
}
//3.循环结束后直接返回max
return max;
}
}
//测试类
import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
//1.创建一个集合用来存储学生对象
ArrayList<Student> list = new ArrayList<>();
//2.创建三个学生对象
Student stu1 = new Student("zhangsan",18,"男");
Student stu2 = new Student("lisi",19,"男");
Student stu3 = new Student("wangwu",19,"男");
//3.把学生对象添加到集合中
list.add(stu1);
list.add(stu2);
list.add(stu3);
//4.调用工具类中的方法
int maxAgeStudent = StudentUtil.getMaxAgeStudent(list);
System.out.println(maxAgeStudent);
}
}
static的注意事项
非静态成员变量又叫做实例变量