@一贤不穿小鞋
对象数组概念
顾名思义,就是数组中的每个元素都是对象。
苹果案列代码
public class Apple {
String color;//颜色
int weight;//重量
public void print() {
System.out.println(color+"的苹果,的重量是:"+weight+"g");
}
}
public class Test {
public static void main(String[] args) {
Apple arr[]=new Apple[4];//一个口袋
Apple a1=new Apple();//4个苹果
a1.color="青色";
a1.weight=50;
Apple a2=new Apple();
a2.color="黄色";
a2.weight=60;
Apple a3=new Apple();
a3.color="绿色";
a3.weight=70;
Apple a4=new Apple();
a4.color="红色";
a4.weight=80;
arr[0]=a1;//对象数组的元素里装对象
arr[1]=a2;
arr[2]=a3;
arr[3]=a4;
for (int i = 0; i < arr.length; i++) {
arr[i].print();
}
}
}
案列:文章排序程序。
public class Wen {
String title;
int see;
public void print() {
System.out.println("标题:"+title+",浏览"+see+"次");
}
public void sort(Wen ws[]) {
//排序,并输出
for (int i = 0; i <ws.length; i++) {
for (int j = 0; j < ws.length-1; j++) {
if (ws[j].see<ws[j+1].see) {
Wen temp;
temp =ws[j];
ws[j]=ws[j+1];
ws[j+1]=temp;
}
}
}
for (int i = 0; i < ws.length; i++) {
ws[i].print();
}
}
}
public class TestWen {
public static void main(String[] args) {
Wen w1=new Wen();
w1.title="我爱java";
w1.see=111;
Wen w2=new Wen();
w2.title="我爱篮球";
w2.see=99;
Wen w3=new Wen();
w3.title="我爱编程公会";
w3.see=666;
Wen ws[]=new Wen[3];
ws[0]=w1;
ws[1]=w2;
ws[2]=w3;
Wen test=new Wen();
test.sort(ws);
}
}
总结:
对象数组概念
苹果案列
文章排序案列