简体   繁体   English

列出Java中的对象

[英]Listing objects in Java

I'm new to Java so my apologies if this is a stupid question. 我是Java的新手,所以如果这是一个愚蠢的问题,我深表歉意。 I'm looking for a way to list all the objects in a class from another class so I don't need to add them to a list as they are created. 我正在寻找一种从另一个类中列出一个类中所有对象的方法,因此在创建对象时不需要将它们添加到列表中。 The idea is then I would be able to use eg for(objects : class) {//do something} but I can't find a way to get a list of them. 当时的想法是我可以使用例如for(objects:class){//做某事},但是我找不到找到它们列表的方法。

Does anyone know of a way to do this if it is possible? 有谁知道这样做的可能方式?

Thank you very much. 非常感谢你。

Java does not support itself. Java不支持自身。 But you can implement your own mechanism. 但是您可以实现自己的机制。 Below is sample code. 下面是示例代码。 I hope this is not requirement for any production level code. 我希望这不是任何生产级别代码的要求。 Because below code will hold references to all the objects and they won't be eligible for garbage collection and may lead to memory leak for high volumes of instances 因为下面的代码将保存对所有对象的引用,因此它们不符合垃圾收集的条件,并且可能导致大量实例的内存泄漏

import java.util.*;
public class HelloWorld
{
  private static final List<HelloWorld> list = new ArrayList<>();

  public HelloWorld(){
    list.add(this);
  }

  public static void main(String[] args)
  {
    HelloWorld object = new HelloWorld();
    System.out.print(list.size());
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM