Tags down


Converting Arraylist implementation to universal in C

By : Ayan Bewafa
Date : October 17 2020, 03:08 PM
Hope this helps You must separate the concerns of your internal list management from those of your customer's list data. Your list management data must be strongly typed, but your view of the customer's list data should be opaque (void*). Your interface design should preserve this separation of concerns.
There is no need to declare or define ArrayListImpl in arraylist.h. Your customers don't need to know about it. Having an ArrayList type is good, but it would suffice if it were simply an opaque handle implemented as an index value, hash or data pointer (void*). Basically, whatever you give your customers for tracking their list, they should be unable to learn any implementation details from its declaration or use. If you do hand them a pointer to an internal management structure, their view of it should be void*. You can always cast from void* to whatever your internal data structure is.
code :
#include <stdbool.h>
#include <stdint.h>

// The current implementation of the API defined herein is not thread safe.s

// ArrayList should be treated as an opaque data object, never intended
// to be dereferenced by client code.
typedef void* ArrayList;

// Define default module initialization.

// InitializeArrayListModule(size_t numLists, size_t incrementSize);
//   Optional module initializer.  The number of lists can grow until memory
//   runs out, but performance may not be optimal and the heap can get 
//   fragmented.  
//   Call this function only if you're going to be allocating more or less 
//   than the default values.
// Arguments:
//   numLists  Number of lists the internal data structures are preallocated 
//   for. Internal
//             default is ARRAYLIST_DEFAULT_NUM_LISTS.
//   incrementSize  Number of additional internal data structures to allocate 
//   when a call to NewArrayList() triggers a realocation of data structures. 
//   Internal default is DEFAULT_INCREMENT_SIZE.
// Returns:
//   true if enough internal data structures can be allocated to support the 
//   specified number of lists.
//   false if allocations failed, the function has been called more than once 
//   or NewArrayList has
//   already been called.
// Notes:
//  1. List management data structures are stored in separate memory from 
//     client's list data.
bool InitializeArrayListModule(size_t numLists, size_t incrementSize);

// NewArrayList(size_t, size_t)
//   The only way to properly initialize an ArrayList object.
// Arguments:
//   initialCapacity Number of initial elements to allocate, must not be 
//   zero.
//   sizeofElements  Size in bytes of each element, must not be zero.
// Returns:
//   A valid ArrayList on success.
//   NULL on failure.
ArrayList NewArrayList(size_t initialCapacity, size_t sizeofElement);

// DestroyArrayList(ArrayList arrayList)
//   The only way to properly destroy an ArrayList object.
// Arguments:
//   arrayList  ArrayList object returned from NewArrayList, or NULL.
// Returns:
//   NULL.
// Example:
//   ArrayList arrayList = NewArrayList(capacity, sizeofElement);
//   arrayList = DestroyArrayList(arrayList);
ArrayList DestroyArrayList(ArrayList arrayList);

// AddArrayListItem(ArrayList, void *item)
//   Copies elementSize bytes from the memory pointed to by item.
// Arguments:
//   arrayList  A valid ArrayList object returned from NewArrayList.
//   element    Pointer to the data to add to the list.
// Returns:
//   true if successful.
bool AddArrayListItem(ArrayList arrayList, void *element);
    #include <stdbool.h>
#include <stdio.h>
//#include "ArrayList.h"

void _UTShowTestResult(char *testFuncName, bool result)
    if (result)
        printf("%s() passed.\n", testFuncName);
        printf("%s() failed.\n", testFuncName);

#define UTShowTestResult(funcName) _UTShowTestResult(#funcName, funcName##())

// In UTArrayList.c
// TODO: Add logging.
#include <limits.h>

// Smoke test: bool InitializeArrayListModule(size_t numLists, size_t incrementSize);
bool UTInitializeArrayListModule()
    return InitializeArrayListModule(1, 4);

// Smoke test: ArrayList NewArrayList(size_t, size_t).
bool UTNewArrayList()
    // Happy path...
    for (size_t capacity = 1; capacity <= (64 * 1024); capacity += 1024)
        for (size_t elementSize = 1; elementSize <= (64 * 1024); elementSize += 1024)
            ArrayList testList = NewArrayList(capacity, elementSize);
            if (NULL == testList)
                return false;

    // TODO: Test that expected failure paths fail gracefully.

    return true;

// Smoke test: ArrayList DestroyArrayList(ArrayList arrayList)
bool UTDestroyArrayList()
    ArrayList arrayList = NewArrayList(1, 1);

    // Verify works with NULL.
    if (NULL != DestroyArrayList(NULL))
        return false;

    // Verify works with valid arrayList object, but don't let the test overwrite it yet.
    if (NULL != DestroyArrayList(&arrayList))
        return false;

    // Verify works twice on same value.
    arrayList = DestroyArrayList(&arrayList); // The correct way to call DestroyArrayList().
    if (NULL != arrayList)
        return false;

    return true;

// Smoke test: bool AddArrayListItem(ArrayList arrayList, void *element)
bool UTAddArrayListItem()
    // TODO: Verify list items are correct and remain in proper order over 
    //       list operations, as soon we have an implementation for iterating 
    //       over the list.
    // TODO: Verify items of different sizes can added successfully.
    const char* str1 = "str1";
    ArrayList arrayList = NewArrayList(2, sizeof(char*));
    return AddArrayListItem(arrayList, str1);

// ArrayList Unit Test Driver.
int main(int argc, char **argv)
    // TODO: As the interface is fleshed out, add unit test calls.
    #include <stdlib.h>
#include "ArrayList.h"

typedef struct _List 
    size_t capacity;
    size_t elementSize;
    size_t count;
    void* data;
} List;

static size_t _listCapacity = ARRAYLIST_DEFAULT_NUM_LISTS;
static size_t _incrementSize = ARRAYLIST_DEFAULT_INCREMENT_SIZE;
static size_t _count = 0;

static List *_lists = NULL;
static List *_nextList = NULL;

// TODO: Add implementations as interfaces and unit tests are added.

static bool _InitializeModule()
    // Always fail to initialize twice!
    if (NULL == _lists)
        _lists = calloc(_listCapacity, sizeof(List));
        _nextList = _lists;
    return (_lists != NULL);

static bool _ReallocateLists()
    List *newLists = calloc(_listCapacity + _incrementSize, sizeof(List));
    if (NULL != newLists)
        for (size_t idx = 0; idx < _listCapacity; idx++)
            newLists[idx] = _lists[idx];
        List *tmp = _lists;
        _lists = newLists;
        _nextList = _lists + _listCapacity;
    return (NULL != _lists);

bool InitializeArrayListModule(size_t numLists, size_t incrementSize)
    if (NULL == _lists)
        _listCapacity = numLists;
        _incrementSize = incrementSize;
    return _InitializeModule();

ArrayList NewArrayList(size_t initialCapacity, size_t sizeofElement)
    if (NULL == _lists)
        if (!_InitializeModule()) return NULL;

    if (_listCapacity < _count)
        if (!_ReallocateLists()) return NULL;

    List *p = &(_lists[_count]);
    p->capacity = initialCapacity;
    p->elementSize = sizeofElement;
    p->data = calloc(initialCapacity, sizeofElement);

    return p;

ArrayList DestroyArrayList(ArrayList arrayList)
    List *p = arrayList;    // Convert from void* to List*.
    List *last = _lists + _listCapacity;
    // Sanity checks...
    bool isInRange = (p >= _lists) && (p <= last);
    bool isAligned = 0 == ((p - _lists) % sizeof(List));
    if (isInRange && isAligned)
        memset(p, 0, sizeof(List));
    return NULL;

bool AddArrayListItem(ArrayList arrayList, void *item)
    // TODO: find the list, use similar logic to how _lists is managed, to add this item to that lists data array.
    // HINT: memcpy(itemAddress, item, sizeofElement);
    return false;

Share : facebook icon twitter icon

How to use ArrayList for such implementation ? or If HashMap is good for it then how to use it for such implementation?

By : Haohua Wang
Date : March 29 2020, 07:55 AM
may help you . Instead of using only one employee object, you could use an ArrayList and use that one.
As you modify data, you should think about when to save it. Possible would be to save every change, or just to save if you change the employee.

Using ArrayList at universal app

By : LoudSoda
Date : March 29 2020, 07:55 AM
hop of those help? There hasn't been a good reason to use ArrayList in new code for the last 9 years, but it's still around for backwards compatibility. With UWP they've taken the opportunity to purge the old legacy.
You can always replace an ArrayList with a List. You can almost always do better to replace it with a List for a more specific type unless you've a heterogeneous collection (one that contains items of lots of different types). Being more specific will generally give you code that is safer, faster (removing some unnecessary casting) and will possibly find some bugs in the original that you can then fix.

Performance: Loop through ArrayList hundreds of times vs converting Arraylist to HashMap and Back?

By : Bips
Date : March 29 2020, 07:55 AM
To fix the issue you can do Yes, for large numbers, a HashMap is beneficial.
Your initial algorithm will take a long time, looping through both lists in nested for loops. This is an O(n2) algorithm. Even assuming 1000 items each in A and B, and assuming a cost of 1 for comparing two individual items, one from A and one from B, you're looking at 500k comparisons (avoiding comparing each item twice). Doing this frequently will cause slow performance.
code :
for each index in B:
    get object b
    put in hash map C values (b, index)

for each a in A:
    if found in hash map C: do something with found object

Converting ArrayList to HashMap, however, selecting choice objects with different variable classes within ArrayList

By : mika
Date : March 29 2020, 07:55 AM
Hope this helps You could try with a simple for each loop:
code :
// Note the Map type change to Double!
HashMap<String, Double> typeToAvgAttack = new HashMap<String, Double>();

// Intermediate map to store list of all attack values per type
HashMap<String, List<Integer>> typeToAttack = new HashMap<String, List<Integer>>();

for (Pokemon pokemon: pokemonList) {
    String type = pokemon.getType();
    int attack = pokemon.getAttack();

    // the map is empty at start, we need to check for the keys (pokemon type) existance
    List<Integer> attackValues = typeToAttack.get(type); 
    if (attackValues == null) {
        typeToAttack.put(type, attackValues = new ArrayList());

// Iterate over map keys to calculate the average
for (String type : typeToAttack.keySet()) {
    List<Integer> attackValues = typeToAttack.get(type);
    double average = calculateAverage(attackValues);
    typeToAvgAttack.put(type, average);
public static double calculateAverage(List <Integer> values) {
    double sum = 0d;
    if(!values.isEmpty()) {
        for (Integer value: values) {
            sum += value;
        return sum / values.size();
    return sum;

Converting ArrayList<ArrayList<String>> to ArrayList<ArrayList<Integer>>

By : AddNoth'
Date : September 19 2020, 11:00 PM
it helps some times I have been trying to convert string of ArrayList> to ArrayList> , You can achieve this using Stream API:
code :
ArrayList<ArrayList<String>> list = ...

List<List<Integer>> result = list.stream()
    .map(l -> l.stream().map(Integer::parseInt).collect(Collectors.toList()))
ArrayList<ArrayList<String>> list = ...

ArrayList<ArrayList<Integer>> result = list.stream()
  .map(l -> l.stream().map(Integer::parseInt).collect(Collectors.toCollection(ArrayList::new)))
Related Posts Related Posts :
  • atan2f vs fmodf vs just plain subtraction
  • C reading file into 2D array
  • How to use recursion to determine if path exists between two nodes in graph?
  • SQLite: trouble building FTS5 loadable extension
  • Common words check loop doesn't work
  • How to get Mouse input inside a C console program on Windows-10?
  • Prevent external calls to functions inside lib file
  • Both struct variables getting same value inside union
  • instructions after scanf() call get called twice
  • Is it possible to override SSH expecting password input from /dev/tty in C
  • Assigning reference of variable to pointer results in unintended behavior
  • Is it safe to swap values of an unknown type
  • Defining something to itself in C preprocessor
  • Leibniz function in c
  • Why do major compilers use typedef for stdint.h but use #define for stdbool.h?
  • Using long double in C gives weird results after subtraction
  • Code seems to continue running after return statement (in C)
  • C Program Works in GDB But Not Normally
  • Trying to get a variable equal to other variables in C
  • How do I create a Storable instance for a recursive type?
  • Segmentation Fault in using a node struct
  • How can I copy a dialogs position coordinates into another dialogs?
  • Why does gcc produce different compiled binaries for programs that use different forms of integer literals?
  • Program in c that takes an array and prints out and then finds its mean max and min. Not working properly
  • Unable to assign structure variable to another structure variable
  • Metamorphic Example Code
  • GCC vs Clang copying struct flexible array member
  • 2nd char array overwriting 1st char array after fread from file
  • Not getting all results shifting my array
  • Sysmalloc: Assertion
  • Hungarian Algorithm - Wikipedia method doesn't work for this example
  • Premultiplying image alpha efficiently
  • General Fibonacci, why is it overflowing?
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com