实例的输出ID

时间:2013-10-17 09:04:08

标签: java static instantiation

我想创建一个类的5个实例,但不再创建(第6次实例化时出现错误消息)。此外,我希望能够以自定义顺序调用每个对象字段(在本例中为id),因此我需要这些对象的引用变量,因为我的getInstance()必须是静态方法。如何以与创建它们相反的顺序输出每个对象的id。希望这是有道理的,如果不是只告诉我你通常会做这种事情。

public class JustFive {
    private static int i=0;
    private int id;
    public JustFive(int n){
        this.id=n;
    }
    public static void main(String[] args) throws Exception {
         getInstance();
         getInstance();
         getInstance();
         getInstance();
         getInstance();
    }
    private static JustFive getInstance() throws Exception{
        if(i<5) {
            i++;
            System.out.println(i+" instance created ");
            return new JustFive(i*1000);
        } else
            throw new Exception("Can't create more than 5 instances of this class");
    }
    private int getId(){
        return this.id;
    }
}

2 个答案:

答案 0 :(得分:0)

创建五个JustFive个实例,将它们放在List<JustFive>中,然后使用Comparator<JustFive>id的降序对它们进行排序。

public static void main(String[] args) throws Exception {
    List<JustFive> jfs = Arrays.asList(getInstance(), getInstance(), getInstance(), getInstance(), getInstance());
    Collections.sort(jfs, new Comparator<JustFive>(){
        @Override
        public int compare(JustFive o1, JustFive o2) {
            return -1 * new Integer(o1.id).compareTo(o2.getId());
        }
    });
    for (JustFive justFive : jfs) {
        System.out.println(justFive.getId());
    }
}

<强>输出

1 instance created 
2 instance created 
3 instance created 
4 instance created 
5 instance created 
5000
4000
3000
2000
1000

答案 1 :(得分:0)

import java.util.List;

public static void main(String[] args) throws Exception {
     List<JustFive> elems = new ArrayList<>();
     for (int i = 0; i < 5; i++) { 
         elems.add(getInstance());
     }
     // print in reverse order
     for (int i = elems.size() - 1; i >= 0; i--) { 
         System.out.println(elems.get(i).getId());
     }
}