简体   繁体   中英

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. eg: after user see array position 0 (Marie) info, remove array position 0 from memory.

What is the best way to do it? array, arraylist, arraymap...? 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. You can use offer or add methods to add item and poll() to remove first item

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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