C++: vector of arrays

In C++ arrays cannot be stored in vectors. This restriction is due to the fact that arrays cannot be copy constructed or assigned. For example, this won’t compile in c++

To work around this limitation, c++11 has introduced a new container called std::array. std::array is just a template class that encapsulates a static array. It cannot be resized and its size should be know at compile time. Here is a small example on how to create a vector of arrays.

Java LinkedHashMap: Changing the order of items

The answer is you can’t change the order of elements in a LinkedHashMap in Java directly. This means that you don’t have direct control over the order of elements in a LinkedHashMap. It has the ability to only maintain the insertion order or access order. There are no methods or iterators through which you can insert an element at a desired position. The only possible way to insert an element into LinkedHashMap is through put method inherited from Map interface.

LinkedHashMap<String, Integer> map = new LinkedHashMap<String, Integer>();
map.put("One", 1);

This gives you no way to insert at a particular position. The entrySet method returns you the ordered Set of its entries. But you cannot add a new element into the LinkedHashMap through the entrySet because the LinkedHashMap.Entry class is private to LinkedHashMap and is invisible outside. So there is no way to create a custom entry instance and insert it into the entrySet.

So, if you are using LinkedhashMap for

  1. Faster access times (Offered by HashMap) O(1)
  2. Faster add and removal times (Offered by HashMap) O(1)
  3. Maintaining order of insertion (Offered by LinkedList)
  4. Iterating through order of insertion (Offered by LinkedList)

you made the right choice. But if your application demands that the order of elements may change at some point in time after insertion, LinkedHashMap is not your option.

GoLang: Marshall slice and map members of struct into JSON

Go has an incredibly user friendly built-in JSON encoder and decoder. One can create a struct with slice and map members and expect the encoding/json package to marshal and un-marshal it without any hassle. Here is a showcase program of how to marshal and unmarshal a struct containing slice and map members:

Output

Before marshaling:
IntF: 5
StringF: 55
FloatF: 55.500000
SliceF: [5 55 555]
MapF: map[5:%!s(int=5) 55:%!s(int=55) 555:%!s(int=555)]

Marshalled data: {“IntF”:5,”StringF”:”55″,”FloatF”:55.5,”SliceF”:[“5″,”55″,”555″],”MapF”:{“5″:5,”55″:55,”555″:555}}

Unmarshaled data:
{“IntF”:555,”StringF”:”5″,”FloatF”:5.555,”SliceF”:[“555″,”55″,”5″],”MapF”:{“5.5″:5.5,”55.5″:55.5,”555.5″:555.5}}

After unmarshaling
IntF: 555
StringF: 5
FloatF: 5.555000
SliceF: [555 55 5]
MapF: map[5.5:%!s(int=0) 55.5:%!s(int=0) 555.5:%!s(int=0)]