定义工具类
例1
package a02staticdemo2 ;
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++ ) {
if ( i == arr. length - 1 ) {
sb. append ( arr[ i] ) ;
} else {
sb. append ( arr[ i] ) . append ( ", " ) ;
}
}
sb. append ( "]" ) ;
return sb. toString ( ) ;
}
public static double getValue ( double [ ] arr) {
double sum = 0 ;
for ( int i = 0 ; i < arr. length; i++ ) {
sum = sum + arr[ i] ;
}
return sum/ arr. length;
}
}
package a02staticdemo2 ;
public class testdemo {
public static void main ( String [ ] args) {
int [ ] arr1 = {
1 , 2 , 3 , 4 , 5 } ;
String str = ArrayUtil . printArr ( arr1) ;
System . out. println ( str) ;
double [ ] arr2 = {
1.2 , 2.3 , 3.4 , 4.5 , 5.6 } ;
double ave = ArrayUtil . getValue ( arr2) ;
System . out. println ( ave) ;
}
}
例2
package a03staticdemo3 ;
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;
}
}
package a03staticdemo3 ;
import java. util. ArrayList ;
public class StudentUtil {
private StudentUtil ( ) {
}
public static int getMaxAgeStudent ( ArrayList < Student > list) {
int max = list. get ( 0 ) . getAge ( ) ;
for ( int i = 1 ; i < list. size ( ) ; i++ ) {
int temp = list. get ( i) . getAge ( ) ;
if ( temp > max) {
max = temp;
}
}
return max;
}
}
package a03staticdemo3 ;
import java. util. ArrayList ;
public class testdemo {
public static void main ( String [ ] args) {
ArrayList < Student > list = new ArrayList < > ( ) ;
Student stu1 = new Student ( "zhangsan" , 23 , "男" ) ;
Student stu2 = new Student ( "lisi" , 24 , "女" ) ;
Student stu3 = new Student ( "wangwu" , 25 , "男" ) ;
list. add ( stu1) ;
list. add ( stu3) ;
list. add ( stu3) ;
int maxAgeStudent = StudentUtil . getMaxAgeStudent ( list) ;
System . out. println ( maxAgeStudent) ;
}
}