连接多个的ArrayList引用 [英] Concatenate multiple arraylists references

查看:74
本文介绍了连接多个的ArrayList引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我有3个的ArrayList打了个比方图书报纸杂志和一个ArrayList的名为资源

如果你做这样的事情: =资源书; 那么资源将指向相同的内存位置的书籍

但你怎么能添加到这个资源末其他两个的ArrayList的开始这样的资源将包含所有的ArrayList?类似的回忆的ArrayList引用串联。


解决方案

  1. 如果你想要的书,报纸和杂志的内容的ArrayList 将出现在一个的ArrayList 资源,那么你可以使用 ArrayList.addAll(集合)功能:追加所有元素的指定集合中这个列表的末尾,在使他们由指定集合的​​迭代器返回。

      resources.addAll(书);
    resources.addAll(报纸);
    resource.addAll(杂志);


  2. 您想创建一个的ArrayList 将包含的ArrayList的元素:

     的ArrayList< ArrayList的<串GT;>资源=新的ArrayList<>();
     resources.add(书);
     resources.add(报纸);
     resources.add(杂志);


假设书籍,杂志和报纸的ArrayList 的类型是的ArrayList<弦乐> 。但是,如果第二个是你的目标,然后我想还是你声明的资源为的HashMap<弦乐,ArrayList的<弦乐>>

 的HashMap<弦乐,ArrayList的<串GT;>资源=新的HashMap<>();
            //与图书\\报纸\\杂志的元素的类型替换字符串
    resources.put(书,书);
    resources.put(报,报纸);
    resources.put(杂志,杂志);

So I have 3 arraylists called for example books, newspapers, magazines and one arraylist called resources.

If you do something like : resources = books; then resources will point to the same memory location as books.

But how can you add to this resources at the end the start of the other two arraylists so the resources will contain all arraylists? Something like concatenation of arraylists memories references.

解决方案

  1. If you want the elements of book, newspaper and magazine ArrayLists will appear in one ArrayList resources, then you can make use of ArrayList.addAll(Collection) function: Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator.

    resources.addAll(book);
    resources.addAll(newspaper);
    resource.addAll(magazine);
    

  2. You want to create an ArrayList which will contain the ArrayLists as element:

     ArrayList<ArrayList<String>>resources = new ArrayList<>();
     resources.add(book);
     resources.add(newspaper);
     resources.add(magazine);
    

Assumed that the type of book, magazine and newspaper ArrayLists is ArrayList<String>. However, if second one is your target then i think it is better you declare resources as an 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);

这篇关于连接多个的ArrayList引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆