本帖最后由 古银平 于 2012-10-6 20:23 编辑
- package day18;
- import java.util.*;
- class Person
- {
- private String name;
- private int age;
- Person(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public int hashCode()
- {
- return name.hashCode()+age*29;
- }
- public int compareTo(Person s)
- {
- int num = new Integer(this.age).compareTo(new Integer(s.age));
- if(num==0)
- return this.name.compareTo(s.name);
- return num;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Person))
- throw new ClassCastException("类型不匹配!");
- Person s = (Person)obj;
- return this.name.equals(s.name) && this.age==s.age;
- }
- public String toString()
- {
- return name+": :"+age;
- }
- }
- class Duizhan
- {
- private LinkedList<Person> link; //这里用List接口的LinkedList类
- Duizhan()
- {
- link=new LinkedList<Person>();
- }
- public void myAdd(Person p)
- {
- link.addFirst(p); //讲存进的元素都放在列表的开头
- }
- public Person myGet()
- {
- return link.removeFirst(); //取出第一个元素,最后存进去的就是起一个元素
- }
- public boolean isNull()
- {
- return link.isEmpty();
- }
- }
- class DuizhanDemo {
- public static void main(String[] args)
- {
- Duizhan dl = new Duizhan();
- dl.myAdd(new Person("lisi1",20));
- dl.myAdd(new Person("lisi2",23));
- dl.myAdd(new Person("lisi3",21));
- dl.myAdd(new Person("lisi4",22));
- while(!(dl.isNull()))
- {
- System.out.println(dl.myGet());
- }
- }
- }
- 堆栈就是先进后出,出来的结果是lisi4......lisi1,这我写的,你看看那把
复制代码 |