简体   繁体   English

用Java创建对象列表

[英]Creating a list of objects in Java

So I was thinking of creating a list of objects like this 所以我想创建一个像这样的对象列表

ArrayList<Obj> lst = new ArrayList<Obj>(10);
for (int i = 0; i < 10; i++) {
  Obj elem = new Obj();
  lst.add(elem);
}

Is this legal or do I have to worry about Object 1 getting trashed when the elem reference starts pointing to Object 2? 这是合法的还是我必须担心当elem引用开始指向对象2时对象1被删除? If it's illegal, how might I do it otherwise? 如果这是非法的,我怎么办呢? Is there a way to automatically generate ten different reference names? 有没有办法自动生成十个不同的参考名称?

Garbage Collector will remove objects only when there are no references pointing to it. 仅当没有指向它的引用时,垃圾收集器才会删除对象。 In your case, your list will be pointing to 10 distinct Object objects and they are safe until you lose reference to lst Object. 在您的情况下,您的列表将指向10个不同的Object对象,它们是安全的,直到您失去对lst Object的引用。

It's perfectly legal. 这完全合法。 Your ArrayList will contain a reference to the object you just created, so it will not be GCed. 您的ArrayList将包含对您刚刚创建的对象的引用,因此它不会被GCed。

Your approach is perfectly valid. 你的方法是完全有效的。 You will end up with a list of ten distinct objects. 最终将得到十个不同对象的列表。

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

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