简体   繁体   English

将数据存储在数组中的最佳方法

[英]Best way to store data in array

I get from database some informations and I'd like to store it like:我从数据库中获取一些信息,我想将其存储为:

Person[0] {name:"Marie", email:"marie@marie.com", adress:"address marie"}
Person[1] {name:"Josh", email:"josh@josh.com", adress:"address josh"}
...

So I can add more items, access items using position and after user show each position, remove it from array.所以我可以添加更多项目,使用 position 访问项目,并在用户显示每个 position 后,将其从数组中删除。 eg: after user see array position 0 (Marie) info, remove array position 0 from memory.例如:在用户看到数组 position 0 (Marie) 信息后,从 memory 中删除数组 position 0。

What is the best way to do it?最好的方法是什么? array, arraylist, arraymap...?阵列,arraylist,阵列映射...? How to declare, add and remove positions infos?如何声明、添加和删除职位信息? Thanks.谢谢。

I guess you can use LinkedList may be, it provides constant O(1) time for adding item at last and removing first item.我猜你可以使用LinkedList ,它提供了constant O(1)时间来最后添加项目和删除第一个项目。 You can use offer or add methods to add item and poll() to remove first item您可以使用offeradd方法添加项目和poll()删除第一个项目

You can do below operations您可以执行以下操作

val list = LinkedList<String>() 
list.add("Android") // add items to the end
list.add(5, "Hello") //adds item at mentioned position
list.poll() // removes first item
list.removeAt(4) //removes item at certain position
list.pollLast() // removes last item

To achieve what you are expecting, you could do something like this:为了达到您的期望,您可以执行以下操作:

    List<Map<String,String>> data = new ArrayList();
    Map<String,String> map = new HashMap();
    
    map.put("name","Marie");
    map.put("email","marie@marie.com");
    map.put("adress","address marie");

    
    data.add(map);
    
    System.out.println(data.get(0));

For inserting multiple items:对于插入多个项目:

    List<Map<String,String>> data = new ArrayList();
    Map<String,String> map = new HashMap();
    
    for(Class a : object)
    {
       map.put("name",a.name); //a.name is just from my imagination only. use your own aproach to get name.
       map.put("email",a.email);
       map.put("address",a.address);
       data.add(map);
    }
 
    System.out.println(data.get(0));

Use ArrayList instead of Array for store data使用 ArrayList 而不是 Array 存储数据

String[] Person = {name:"Marie", email:"marie@marie.com", adress:"address marie"}
Person[1] {name:"Josh", email:"josh@josh.com", adress:"address josh"}
ArrayList<String> data = new ArrayList()<String>;
data.add(Person);

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

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