The answers is incorrect:
The output is:
[a, b, c]
2
[c, b, a]
-4
Therefore, the correct answer is : 2, -4
About Question enthuware.ocpjp.v17.2.3743 :
Moderator: admin
-
- Posts: 24
- Joined: Wed Sep 28, 2022 9:41 am
- Contact:
-
- Site Admin
- Posts: 10066
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3743 :
No, it may not necessarily print -4 for the second search statement. The API clearly says that if the list is not sorted by its natural order then the result will be undefined. So, even if it prints -4, it is not guaranteed to print -4.
If you like our products and services, please help us by posting your review here.
-
- Posts: 24
- Joined: Wed Sep 28, 2022 9:41 am
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3743 :
I run this code 10x, in Intellij...
And the answer is:
[a, b, c]
2
[c, b, a]
-4
But thats ok, I will consider your answers as correct.
Tahnks
Code: Select all
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class BinarySearchTest {
public static void main(String[] args) {
List<String> letters = new ArrayList<String>();
letters.addAll(List.of("a", "c", "b"));
Collections.sort(letters);
System.out.println(letters);
System.out.println(Collections.binarySearch(letters, "c"));
Collections.reverse(letters);
System.out.println(letters);
System.out.println(Collections.binarySearch(letters, "c"));
}
}
[a, b, c]
2
[c, b, a]
-4
But thats ok, I will consider your answers as correct.
Tahnks
Last edited by admin on Wed Jul 26, 2023 9:57 am, edited 1 time in total.
Reason: Please put code inside [code] [/code]
Reason: Please put code inside [code] [/code]
-
- Site Admin
- Posts: 10066
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3743 :
You may run it a thousand times and it will print the same because that depends on the library code contained in the JDK that you are using. But since the API gives no guarantee the next version of the JDK may print something else. You can't depend on this output.
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: No registered users and 140 guests