1

我想创建一个类的 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;
    }
}
4

2 回答 2

0

创建五个JustFive实例,将它们放在 a 中List<JustFive>,然后使用 aComparator<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
于 2013-10-17T09:10:47.733 回答
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());
     }
}
于 2013-10-17T09:11:12.250 回答