Java Challenge: Predict the Output of This Code

🚀 Java Challenge — Can You Predict the Output? 🤔 Take a careful look at this code and mentally run it for a moment: ``` List<Integer> alpha = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7)); List<Integer> beta = alpha.subList(2, 5); System.out.println(alpha); // ? System.out.println(beta); // ? beta.add(1, 99);      // System.out.println(alpha); // ? System.out.println(beta); // ? alpha.add(100);      // System.out.println(alpha); // ? System.out.println(beta); // ? ``` 🧠 Think about it: Does adding to beta affect alpha? Will it modify the size of the original list? Anything dangerous after the last update? 💬 Drop your expected output in the comments — let’s see how deep your Java knowledge goes! 😎 #Java #TrickyCode #Collections #CodeChallenge #DeveloperCommunity #BrainTeaser

Great one!! subList() always tricks people because it’s just a view on the original list. Updating beta updates alpha too After beta.add(1, 99) both lists change But once you call alpha.add(100), the backing list structure changes. ConcurrentModificationException when printing beta Moral of the story: subList() is powerful but handle with care 😄

[1, 2, 3, 4, 5, 6, 7] [3, 4, 5] [1, 2, 3, 99, 4, 5, 6, 7] [3, 99, 4, 5] [1, 2, 3, 99, 4, 5, 6, 7, 100] Exception in thread "main" java.util.ConcurrentModificationException Adding to beta affects alpha because beta is a view, not a copy. It modifies the original alpha list. After the last update, further access to beta throws an exception due to modification of the backing list.

See more comments

To view or add a comment, sign in

Explore content categories