构建Person类(属性:名字、年龄、工作岗位),创建三个对象,并且根据对象的年龄或名字长度来进行冒泡排序
package chapter08.homework.test01;
public class homework01 {
public static void main(String[] args) {
Person[] persons = new Person[3];
persons[0] = new Person("tom",66,"软件工程师");
persons[1] = new Person("jack",20,"java工程师");
persons[2] = new Person("smith",21,"python工程师");
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i]);//默认调Person的toString方法
}
Person tem = null;
for (int i = 0; i < persons.length-1; i++) {
for (int j = 0; j < persons.length-1-i; j++) {
//前面人的年龄小于后面的,就交换
// if (persons[i].getAge()>persons[i+1].getAge()) {
// tem=persons[i];
// persons[i]=persons[i+1];
// persons[i+1]= tem;
// }
//按照名字长度排序
if (persons[i].getName().length()>persons[i+1].getName().length()) {
tem=persons[i];
persons[i]=persons[i+1];
persons[i+1]= tem;
}
}
}
System.out.println("*********************");
for (int i = 0; i < persons.length; i++) {
System.out.println(persons[i]);//默认调Person的toString方法
}
}
}
class Person{
private String name;
private int age;
private String job;
public Person(String name, int age, String job) {
this.name = name;
this.age = age;
this.job = job;
}
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 getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", job='" + job + '\'' +
'}';
}
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » Java继承练习
发表评论 取消回复