can someone explain me why do always we need to reference the index 2 in order to get the solution? Thanks :)
why index 2?
You must be signed in to leave a comment
27 October 2020, 06:23
Not my answer. From the post section "I felt the same way too, it just wasn't making sense, especially with Stackoverflow ,until I started printing out my solutions. I realised that when you declare and initialize a StackTraceElement , you are actually creating an array. When you print out the different indices of that array you get to see the 'story' or stacktrace.In the problem 'Who called me' I ended up just copying and pasting the solution because I kept passing the wrong index .When I started to print them out it was clear as day. 0 index shows the beginning of the programme , the next(index 1) shows where the current method was declared and initialized , and the next method (index 2 ) shows where the method was first called and so on.It helped me quite alot ,maybe it will work for you too, to get a clearer picture of what you are actually working with.Oh! and the stacktraces for the methods are not equal"
27 October 2020, 07:37
yes, exactly, that's the way how it is working. getMethodName() Thread.currentThread().getStackTrace()Thread.currentThread().getStackTrace() returns an array with StackTraceElements. These you can output and see the last called methods (with getMethodName the names of these methods). Index 0 is the get getStackTrace()) call, 1 the method in which you called getStackTrace and 2 the last method. An excellent source, if you do not understand things, are the Java docs.