创建一个Person类,该类中包含姓名、性别、年龄等属性,
创建10个Person对象,加入到Vector中,对创建一个Person类,该类中包含姓名、性别、年龄等属性,
创建10个Person对象,加入到Vector中,对Vector对里面的Person按年龄进行排序对里面的Person按年龄进行排序
import java.util.Vector;
public class Person
{
String name = null;
char sex = '男';
int age = 1;
Person()
{
}
Person(String name)
{
this(name,'男',1);
}
Person(String name,int age)
{
this(name,'男',age);
}
Person(String name,char sex,int age)
{
this.name = name;
this.sex = sex;
this.age = age;
} public static void main(String[] args)
{
Vector v = new Vector();
int[] age = {15,46,14,13,12,87,8,57,96,36};
String[] name = {"A","B","C","D","E","F","G","H","I","J"};
Person[] person = new Person[10];
for(int i = 0;i <person.length;i++)
{
person[i] = new Person();
person[i].name = name[i];
person[i].age = age[i];
v.addElement(person[i]);
}
System.out.println(v.toString());
}
}为什么toString 显示的是内存地址呢..? 后面有点不会做了.- -# 求解
创建10个Person对象,加入到Vector中,对创建一个Person类,该类中包含姓名、性别、年龄等属性,
创建10个Person对象,加入到Vector中,对Vector对里面的Person按年龄进行排序对里面的Person按年龄进行排序
import java.util.Vector;
public class Person
{
String name = null;
char sex = '男';
int age = 1;
Person()
{
}
Person(String name)
{
this(name,'男',1);
}
Person(String name,int age)
{
this(name,'男',age);
}
Person(String name,char sex,int age)
{
this.name = name;
this.sex = sex;
this.age = age;
} public static void main(String[] args)
{
Vector v = new Vector();
int[] age = {15,46,14,13,12,87,8,57,96,36};
String[] name = {"A","B","C","D","E","F","G","H","I","J"};
Person[] person = new Person[10];
for(int i = 0;i <person.length;i++)
{
person[i] = new Person();
person[i].name = name[i];
person[i].age = age[i];
v.addElement(person[i]);
}
System.out.println(v.toString());
}
}为什么toString 显示的是内存地址呢..? 后面有点不会做了.- -# 求解
{ /**
* @param args
*/
public static void main(String[] args)
{
// TODO Auto-generated method stub
Vector<Person> myVec = new Vector<Person>();
myVec.add(new Person("zhang",true,11));
myVec.add(new Person("wang",false,21));
myVec.add(new Person("li",true,51));
myVec.add(new Person("zhao",false,43));
myVec.add(new Person("liu",true,7));
myVec.add(new Person("deng",true,87));
myVec.add(new Person("jiang",false,20));
myVec.add(new Person("mao",true,21));
myVec.add(new Person("zhu",true,15));
myVec.add(new Person("qin",true,70));
System.out.println("before:"+myVec);
Collections.sort(myVec);
System.out.println("after:"+myVec);
}}class Person implements Comparable<Person>
{
private String name;
private boolean sex; //true男 false女
private int age;
Person(String name, boolean sex, int age)
{
try
{
if(age<=0)
throw new Exception();
this.name = name;
this.sex = sex;
this.age = age;
}
catch(Exception ex)
{
System.out.println("出现异常");
}
}
public String getSex()
{
if(sex)
return "M";
else
return "F";
}
public String toString()
{
return "["+name+","+getSex()+","+age+"]";
}
public int compareTo(Person other)
{
return (age-other.age);
}
}