所以我有 3 个数组列表,例如 books
、newspapers
、magazines
和一个名为 resources
的数组列表。
如果您执行以下操作:resources = books;
,那么资源将指向与 books 相同的内存位置。
但是如何在其他两个数组列表的末尾添加到此资源
,以便资源包含所有数组列表?类似于数组列表内存引用的串联。
最佳答案
如果你想要书报杂志的元素
ArrayLists
将出现在ArrayList
中resources
,那么您可以使用ArrayList.addAll(Collection)
功能:将指定集合中的所有元素按照指定集合的迭代器返回的顺序追加到此列表的末尾。resources.addAll(book); resources.addAll(newspaper); resource.addAll(magazine);
您想要创建
ArrayList
其中将包含 ArrayLists 作为元素:ArrayList<ArrayList<String>>resources = new ArrayList<>(); resources.add(book); resources.add(newspaper); resources.add(magazine);
假设书籍、杂志和报纸的类型ArrayLists
是 ArrayList<String>
。但是,如果第二个是您的目标,那么我认为最好将资源声明为 HashMap<String, ArrayList<String>>
.
HashMap<String, ArrayList<String>>resources = new HashMap<>();
// replace String with the type of the elements of book\newspaper\magazine
resources.put("book", book);
resources.put("newspaper", newspaper);
resources.put("magazine", magazine);
关于java - 连接多个数组列表引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20021410/