initialization interview questions
Top initialization frequently asked interview questions
I am aware that you can initialize an array during instantiation as follows:
String[] names = new String[] {"Ryan", "Julie", "Bob"};
Is there a way to do the same thing with an ArrayList? Or must I add the contents individually with array.add()
?
Source: (StackOverflow)
I want to create a list of options for testing purposes. At first, I did this:
ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");
Then I refactored the code as follows:
ArrayList<String> places = new ArrayList<String>(
Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));
Is there a better way to do this?
Source: (StackOverflow)
If 'Test' is an ordinary class, is there any difference between:
Test* test = new Test;
and
Test* test = new Test();
Source: (StackOverflow)
I want to initialize a struct element, split in declaration and initialization. This is what I have:
typedef struct MY_TYPE {
boolean flag;
short int value;
double stuff;
} MY_TYPE;
void function(void) {
MY_TYPE a;
...
a = { true, 15, 0.123 }
}
Is this the way to declare and initialize a local variable of MY_TYPE
in ANSI C (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?
Update I ended up having a static initialization element where I set every subelement according to my needs.
Source: (StackOverflow)
I need to create a Set
with initial values.
Set<String> h = new HashSet<String>();
h.add("a");
h.add("b");
Is there a way to do this in one command?
Source: (StackOverflow)
How would you initialise a static Map in Java?
Method one: Static initializer
Method two: instance initialiser (anonymous subclass)
or
some other method?
What are the pros and cons of each?
Here is an example illustrating two methods:
import java.util.HashMap;
import java.util.Map;
public class Test {
private static final Map<Integer, String> myMap = new HashMap<Integer, String>();
static {
myMap.put(1, "one");
myMap.put(2, "two");
}
private static final Map<Integer, String> myMap2 = new HashMap<Integer, String>(){
{
put(1, "one");
put(2, "two");
}
};
}
Source: (StackOverflow)
I have a large array in C (not C++ if that makes a difference). I want to initialize all members to the same value. I could swear I once knew a simple way to do this. I could use memset()
in my case, but isn't there a way to do this that is built right into the C syntax?
Source: (StackOverflow)
Which method of checking if a variable has been initialized is better/correct?
(Assuming the variable could hold anything (string, int, object, function, etc.))
if (elem) { // or !elem
or
if (typeof(elem) !== 'undefined') {
or
if (elem != null) {
Source: (StackOverflow)
This question already has an answer here:
Is there some way of initializing a Java HashMap like this?:
Map<String,String> test =
new HashMap<String, String>{"test":"test","test":"test"};
What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastet way to put some "final/static" values in a map that never change and are known in advance when crerating the Map.
Source: (StackOverflow)
What is the best way to initialize a private, static data member in C++? I tried this but it gives me weird linker errors:
class foo
{
private:
static int i;
};
int foo::i = 0;
I'm guessing this is because I can't initialize a private member from outside the class. So what's the best way to do this?
Source: (StackOverflow)
I can create an array and initialize it like this:
int a[] = {10, 20, 30};
How do I create a std::vector
and initialize it similarly elegant?
The best way I know is:
std::vector<int> ints;
ints.push_back(10);
ints.push_back(20);
ints.push_back(30);
Is there a better way?
Source: (StackOverflow)
I'm trying to find a convenient way to initialise 'pod' C++ structs. Now, consider the following struct:
struct FooBar {
int foo;
float bar;
};
// just to make all examples work in C and C++:
typedef struct FooBar FooBar;
If I want to conveniently initialise this in C (!), I could simply write:
/* A */ FooBar fb = { .foo = 12, .bar = 3.4 }; // illegal C++, legal C
Note that I want to explicitly avoid the following notation, because it strikes me as being made to break my neck if I change anything in the struct in the future:
/* B */ FooBar fb = { 12, 3.4 }; // legal C++, legal C, bad style?
To achieve the same (or at least similar) in C++ as in the /* A */
example, I would have to implement an idiotic constructor:
FooBar::FooBar(int foo, float bar) : foo(foo), bar(bar) {}
// ->
/* C */ FooBar fb(12, 3.4);
Which is good for boiling water, but not suitable for lazy people (laziness is a good thing, right?). Also, it is pretty much as bad as the /* B */
example, as it does not explicitly state which value goes to which member.
So, my question is basically how I can achieve something similar to /* A */
or better in C++?
Alternatively, I would be okay with an explanation why I should not want to do this (i.e. why my mental paradigm is bad).
EDIT
By convenient, I mean also maintainable and non-redundant.
Source: (StackOverflow)
(Note: This question is about not having to specify the number of elements and still allow nested types to be directly initialized.)
This question discusses the uses left for a C array like int arr[20];
. On his answer, @James Kanze shows one of the last strongholds of C arrays, it's unique initialization characteristics:
int arr[] = { 1, 3, 3, 7, 0, 4, 2, 0, 3, 1, 4, 1, 5, 9 };
We don't have to specify the number of elements, hooray! Now iterate over it with the C++11 functions std::begin
and std::end
from <iterator>
(or your own variants) and you never need to even think of its size.
Now, are there any (possibly TMP) ways to achieve the same with std::array
? Use of macros allowed to make it look nicer. :)
??? std_array = { "here", "be", "elements" };
Edit: Intermediate version, compiled from various answers, looks like this:
#include <array>
#include <utility>
template<class T, class... Tail, class Elem = typename std::decay<T>::type>
std::array<Elem,1+sizeof...(Tail)> make_array(T&& head, Tail&&... values)
{
return { std::forward<T>(head), std::forward<Tail>(values)... };
}
// in code
auto std_array = make_array(1,2,3,4,5);
And employs all kind of cool C++11 stuff:
- Variadic Templates
sizeof...
- rvalue references
- perfect forwarding
std::array
, of course
- uniform initialization
- omitting the return type with uniform initialization
- type inference (
auto
)
And an example can be found here.
However, as @Johannes points out in the comment on @Xaade's answer, you can't initialize nested types with such a function. Example:
struct A{ int a; int b; };
// C syntax
A arr[] = { {1,2}, {3,4} };
// using std::array
??? std_array = { {1,2}, {3,4} };
Also, the number of initializers is limited to the number of function and template arguments supported by the implementation.
Source: (StackOverflow)