【问题标题】:Output ID of instance实例的输出 ID
【发布时间】:2013-10-17 09:04:08
【问题描述】:

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

【问题讨论】:

    标签: java static instantiation


    【解决方案1】:

    创建五个JustFive 实例,将它们放在List&lt;JustFive&gt; 中,然后使用Comparator&lt;JustFive&gt;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
    

    【讨论】:

    • 这行得通.. 但是我怎样才能得到,比如说,只有第三个实例的私有 id ?
    【解决方案2】:
    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());
         }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-11-06
      • 2022-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-03
      • 2017-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多