Code Snippets-based MCQs
Lists & Sets
Table of contents
Easy Level MCQs
-
What will be the output of the following code snippet?
import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); System.out.println(list.size()); } }Answer
3
-
What will the following code snippet print?
import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(1); System.out.println(set.size()); } }Answer
2
-
What will be the output of the following code snippet?
import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("A"); list.add("B"); list.remove(1); System.out.println(list); } }Answer
[A]
-
What will the following code snippet print?
import java.util.LinkedHashSet; public class Example { public static void main(String[] args) { LinkedHashSet<String> set = new LinkedHashSet<>(); set.add("A"); set.add("B"); set.add("C"); for (String s : set) { System.out.print(s + " "); } } }Answer
A B C
-
What will be the output of the following code snippet?
import java.util.Vector; public class Example { public static void main(String[] args) { Vector<Integer> vector = new Vector<>(2); vector.add(1); vector.add(2); vector.add(3); System.out.println(vector.size()); } }Answer
3
-
What will the following code snippet print?
import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); for (int num : list) { System.out.print(num + " "); } } }Answer
1 2 3
-
What will be the output of the following code snippet?
import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<String> set = new TreeSet<>(); set.add("Banana"); set.add("Apple"); set.add("Mango"); System.out.println(set.first()); } }Answer
Apple
-
What will the following code snippet print?
import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<>(); list.add(10); list.add(20); list.addFirst(5); System.out.println(list.get(0)); } }Answer
5
-
What will be the output of the following code snippet?
import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<String> set = new HashSet<>(); set.add("X"); set.add("Y"); set.add("Z"); set.remove("Y"); System.out.println(set.contains("Y")); } }Answer
false
-
What will the following code snippet print?
import java.util.Vector; public class Example { public static void main(String[] args) { Vector<Integer> vector = new Vector<>(); vector.add(1); vector.add(2); vector.set(1, 3); System.out.println(vector.get(1)); } }Answer
3
-
What will happen when the following code snippet is executed?
import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<int> list = new ArrayList<>(); list.add(1); list.add(2); System.out.println(list.size()); } }Answer
Compilation error
Explanation: In Java, generic types cannot be primitive types like
int. Instead, you should use the wrapper classInteger. The correct declaration would beArrayList<Integer> list = new ArrayList<>();. -
What will be the output when the following code snippet is executed?
import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<String> set = new HashSet<>(); set.add("A"); set.add("B"); set.add("C"); for (int i = 0; i < set.size(); i++) { System.out.print(set.get(i) + " "); } } }Answer
Compilation error
Explanation: The
HashSetclass does not have aget(int index)method. Sets in Java do not support indexed access because they are unordered collections. To iterate over a set, you should use an iterator or a for-each loop. -
What will happen when the following code snippet is executed?
import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("Hello"); list.add("World"); list.add(2, "!"); System.out.println(list); } }Answer
[Hello, World, !]
Explanation: The
add(int index, E element)method inserts the specified element at the specified position. Since the list initially has two elements at indices 0 and 1, adding an element at index 2 appends it to the end. Therefore, the list becomes[Hello, World, !]. -
What will be the result of executing the following code snippet?
import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<Integer> set = new TreeSet<>(); set.add(null); set.add(1); set.add(2); System.out.println(set); } }Answer
Runtime error
Explanation: Adding
nullto aTreeSetwill throw aNullPointerExceptionat runtime becauseTreeSetrequires elements to be comparable for sorting, andnullcannot be compared. -
What will happen when the following code snippet is executed?
import java.util.Vector; public class Example { public static void main(String[] args) { Vector<String> vector = new Vector<>(-1); vector.add("A"); vector.add("B"); System.out.println(vector.size()); } }Answer
Runtime error
Explanation: Initializing a
Vectorwith a negative initial capacity will throw anIllegalArgumentExceptionat runtime. -
What will be the output when the following code snippet is executed?
import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("One"); list.add("Two"); list.add("Three"); for (String s : list) { if (s.equals("Two")) { list.remove(s); } } System.out.println(list); } }Answer
Runtime error
Explanation: Removing elements from a list while iterating over it using a for-each loop will throw a
ConcurrentModificationExceptionat runtime. To safely remove elements, use an iterator’sremove()method. -
What will happen when the following code snippet is executed?
import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); for (Integer num : set) { if (num == 2) { set.add(4); } } System.out.println(set.size()); } }Answer
Runtime error
Explanation: Modifying a
HashSetwhile iterating over it will throw aConcurrentModificationExceptionat runtime. -
What will be the output when the following code snippet is executed?
import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("A"); list.add("B"); list.add("C"); System.out.println(list.get(3)); } }Answer
Runtime error
Explanation: The
get(int index)method will throw anIndexOutOfBoundsExceptionif the index is out of range. Since the list has elements at indices 0, 1, and 2, trying to access index 3 will cause a runtime error. -
What will happen when the following code snippet is executed?
import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<String> set = new TreeSet<>(); set.add("Apple"); set.add("apple"); set.add("Banana"); System.out.println(set); } }Answer
[Apple, Banana, apple]
Explanation:
TreeSetsorts elements according to their natural ordering. In Java, uppercase letters come before lowercase letters in Unicode, so “Apple” < “Banana” < “apple”. Therefore, the set will be ordered as[Apple, Banana, apple]. -
What will be the output when the following code snippet is executed?
import java.util.Vector; public class Example { public static void main(String[] args) { Vector vector = new Vector(); vector.add("1"); vector.add(2); for (Object obj : vector) { System.out.print((String) obj + " "); } } }Answer
Runtime error
Explanation: The code attempts to cast an
Integerobject (2) to aString, which will throw aClassCastExceptionat runtime. To avoid this, ensure that all elements are of the same type or handle casting appropriately.
Slightly harder MCQs
-
What will be the output of the following code snippet?
import java.util.HashSet; import java.util.Iterator; public class Example { public static void main(String[] args) { HashSet<Integer> set = new HashSet<>(); set.add(10); set.add(20); set.add(30); Iterator<Integer> it = set.iterator(); while (it.hasNext()) { Integer value = it.next(); if (value % 20 == 0) { it.remove(); } } System.out.println(set); } }Answer
[10, 30]
Explanation: The code removes elements divisible by 20 using an iterator’s
remove()method. Since 20 is divisible by 20, it is removed, leaving[10, 30]in the set. -
What will be the output of the following code snippet?
import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(10); list.add(20); list.add(30); for (int i = 0; i < list.size(); i++) { list.set(i, list.get(i) + 10); } System.out.println(list); } }Answer
[20, 30, 40]
Explanation: The code iterates through the list and increases each element by 10 using the
setmethod. The final list is[20, 30, 40]. -
What will happen when the following code snippet is executed?
import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("A"); list.add("B"); list.add("C"); list.removeFirst(); list.addFirst("D"); System.out.println(list); } }Answer
[D, B, C]
Explanation: The code first removes the first element “A” from the list, and then adds “D” to the beginning. The final list is
[D, B, C]. -
What will happen when the following code snippet is executed?
import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<Integer> set = new TreeSet<>(); set.add(10); set.add(5); set.add(20); set.add(5); System.out.println(set); } }Answer
[5, 10, 20]
Explanation:
TreeSetmaintains a sorted order and does not allow duplicate elements. The final set is[5, 10, 20]. -
What will be the result of executing the following code snippet?
import java.util.Vector; public class Example { public static void main(String[] args) { Vector<String> vector = new Vector<>(); vector.add("A"); vector.add("B"); vector.add("C"); vector.add(1, "D"); vector.remove("C"); System.out.println(vector); } }Answer
[A, D, B]
Explanation: The code inserts “D” at index 1, shifting the elements to the right, and then removes “C”. The final vector is
[A, D, B]. -
What will be the output when the following code snippet is executed?
import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(3); set.add(2); System.out.println(set.size()); } }Answer
3
Explanation:
HashSetdoes not allow duplicate elements, so adding “2” twice has no effect. The set contains 3 unique elements: 1, 2, and 3. -
What will happen when the following code snippet is executed?
import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<Integer> list = new LinkedList<>(); list.add(1); list.add(2); list.add(3); list.addLast(4); list.removeFirst(); System.out.println(list); } }Answer
[2, 3, 4]
Explanation: The code adds 4 to the end of the list and then removes the first element, resulting in the list
[2, 3, 4]. -
What will happen when the following code snippet is executed?
import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<String> set = new TreeSet<>(); set.add("Banana"); set.add("Apple"); set.add("Mango"); System.out.println(set); } }Answer
[Apple, Banana, Mango]
Explanation:
TreeSetstores elements in a natural sorted order. The final set is[Apple, Banana, Mango]. -
What will be the output when the following code is executed?
import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(0, 0); list.remove(2); System.out.println(list); } }Answer
[0, 1, 3]
Explanation: The code inserts
0at the beginning of the list, and then removes the element at index2(which is2), resulting in[0, 1, 3]. -
What will be the output when the following code snippet is executed?
import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<String> set = new HashSet<>(); set.add("apple"); set.add("banana"); set.add("cherry"); set.add("banana"); System.out.println(set.contains("banana")); } }Answer
true
Explanation:
HashSetallows only unique elements, and thecontainsmethod checks if an element exists in the set. Since “banana” is in the set, the output istrue. -
Given a
Studentclass with a constructor that initializes thenameandagefields, what will be the output of the following code snippet?import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Student> students = new ArrayList<>(); students.add(new Student("Alice", 20)); students.add(new Student("Bob", 22)); students.add(new Student("Charlie", 21)); System.out.println(students.size()); } }Answer
3
Explanation: The code adds three
Studentobjects to theArrayList, so the size of the list is 3. -
Given a
Studentclass with anamefield and a methodgetName()that returns the student’s name, what will be the output of the following code snippet?import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<Student> students = new LinkedList<>(); students.add(new Student("Alice")); students.add(new Student("Bob")); students.addFirst(new Student("Eve")); System.out.println(students.getFirst().getName()); } }Answer
Eve
Explanation:
addFirstinserts the student “Eve” at the beginning of the list, sogetFirst().getName()returns “Eve”. -
Given a
Studentclass with fieldsnameandage, what will be the output of the following code snippet?import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Student> students = new HashSet<>(); students.add(new Student("Alice", 20)); students.add(new Student("Bob", 22)); students.add(new Student("Alice", 20)); System.out.println(students.size()); } }Answer
2
Explanation: If the
Studentclass does not overrideequalsandhashCode, the twoStudentobjects with the same data are treated as different objects. So, the size of the set is 2. -
Given a
Studentclass with fieldsnameandage, what will be the output of the following code snippet?import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<Student> students = new TreeSet<>(); students.add(new Student("Alice", 20)); students.add(new Student("Bob", 22)); students.add(new Student("Charlie", 21)); System.out.println(students); } }Answer
Compilation error
Explanation:
TreeSetrequires elements to be comparable, so theStudentclass must implementComparableor provide aComparatorwhen creating theTreeSet. -
Given a
Studentclass with fieldsnameandage, what will be the output of the following code snippet?import java.util.Vector; public class Example { public static void main(String[] args) { Vector<Student> students = new Vector<>(); students.add(new Student("Alice", 20)); students.add(new Student("Bob", 22)); students.add(new Student("Charlie", 21)); students.remove(1); System.out.println(students.size()); } }Answer
2
Explanation: The code removes the student at index 1, so the size of the
Vectorbecomes 2. -
Given a
Studentclass with fieldsnameandgrade, what will be the output of the following code snippet?import java.util.LinkedHashSet; public class Example { public static void main(String[] args) { LinkedHashSet<Student> students = new LinkedHashSet<>(); students.add(new Student("Alice", "A")); students.add(new Student("Bob", "B")); students.add(new Student("Charlie", "C")); for (Student student : students) { System.out.print(student.getName() + " "); } } }Answer
Alice Bob Charlie
Explanation:
LinkedHashSetmaintains the insertion order, so the elements are printed in the order they were added. -
Given a
Studentclass with fieldsnameandgrade, what will be the output of the following code snippet?import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Student> students = new ArrayList<>(); students.add(new Student("Alice", "A")); students.add(new Student("Bob", "B")); students.add(new Student("Charlie", "C")); students.clear(); System.out.println(students.isEmpty()); } }Answer
true
Explanation: The
clear()method removes all elements from the list, making it empty. TheisEmpty()method returnstrue. -
Given a
Studentclass with fieldsnameandmarks, what will be the output of the following code snippet?import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Student> students = new HashSet<>(); students.add(new Student("Alice", 85)); students.add(new Student("Bob", 92)); students.add(new Student("Charlie", 78)); for (Student student : students) { if (student.getMarks() > 80) { System.out.print(student.getName() + " "); } } } }Answer
Alice Bob
Explanation: The code prints the names of students with marks greater than 80, so “Alice” and “Bob” are printed.
-
Given a
Studentclass with fieldsnameandmarks, what will be the output of the following code snippet?import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<Student> students = new TreeSet<>(new Comparator<Student>() { public int compare(Student s1, Student s2) { return s2.getMarks() - s1.getMarks(); } }); students.add(new Student("Alice", 85)); students.add(new Student("Bob", 92)); students.add(new Student("Charlie", 78)); System.out.println(students.first().getName()); } }Answer
Bob
Explanation: The custom comparator sorts students by marks in descending order, so
first()returns “Bob”, who has the highest marks. -
Given a
Studentclass with fieldsnameandmarks, what will be the output of the following code snippet?import java.util.Vector; public class Example { public static void main(String[] args) { Vector<Student> students = new Vector<>(); students.add(new Student("Alice", 85)); students.add(new Student("Bob", 92)); students.add(new Student("Charlie", 78)); students.remove(new Student("Alice", 85)); System.out.println(students.size()); } }Answer
2
Explanation: If the
Studentclass does not overrideequalsandhashCode, theremovemethod won’t find a match, and the size remains unchanged at 3. If it does, the size will be 2. -
Given a
Bookclass with fieldstitleandauthor, what will be the output of the following code snippet?import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Book> books = new ArrayList<>(); books.add(new Book("1984", "George Orwell")); books.add(new Book("Brave New World", "Aldous Huxley")); books.add(new Book("Fahrenheit 451", "Ray Bradbury")); System.out.println(books.size()); } }Answer
3
Explanation: The code adds three
Bookobjects to theArrayList, so the size of the list is 3. -
Given a
Movieclass with fieldstitleandyear, what will be the output of the following code snippet?import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<Movie> movies = new LinkedList<>(); movies.add(new Movie("Inception", 2010)); movies.add(new Movie("The Matrix", 1999)); movies.addFirst(new Movie("Interstellar", 2014)); System.out.println(movies.getFirst().getTitle()); } }Answer
Interstellar
Explanation:
addFirstinserts the movie “Interstellar” at the beginning of the list, sogetFirst().getTitle()returns “Interstellar”. -
Given a
Personclass with fieldsnameandage, what will be the output of the following code snippet?import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Person> people = new HashSet<>(); people.add(new Person("Alice", 30)); people.add(new Person("Bob", 25)); people.add(new Person("Alice", 30)); System.out.println(people.size()); } }Answer
2
Explanation: If the
Personclass does not overrideequalsandhashCode, the twoPersonobjects with the same data are treated as different objects. So, the size of the set is 2. -
Given a
Songclass with fieldstitleandartist, what will be the output of the following code snippet?import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<Song> playlist = new TreeSet<>(); playlist.add(new Song("Bohemian Rhapsody", "Queen")); playlist.add(new Song("Stairway to Heaven", "Led Zeppelin")); playlist.add(new Song("Hotel California", "Eagles")); System.out.println(playlist); } }Answer
Compilation error
Explanation:
TreeSetrequires elements to be comparable, so theSongclass must implementComparableor provide aComparatorwhen creating theTreeSet. -
Given a
Productclass with fieldsnameandprice, what will be the output of the following code snippet?import java.util.Vector; public class Example { public static void main(String[] args) { Vector<Product> products = new Vector<>(); products.add(new Product("Laptop", 1000)); products.add(new Product("Smartphone", 700)); products.add(new Product("Tablet", 500)); products.remove(1); System.out.println(products.size()); } }Answer
2
Explanation: The code removes the product at index 1, so the size of the
Vectorbecomes 2. -
Given a
Cityclass with fieldsnameandpopulation, what will be the output of the following code snippet?import java.util.LinkedHashSet; public class Example { public static void main(String[] args) { LinkedHashSet<City> cities = new LinkedHashSet<>(); cities.add(new City("New York", 8419000)); cities.add(new City("Los Angeles", 3980000)); cities.add(new City("Chicago", 2716000)); for (City city : cities) { System.out.print(city.getName() + " "); } } }Answer
New York Los Angeles Chicago
Explanation:
LinkedHashSetmaintains the insertion order, so the elements are printed in the order they were added. -
Given an
Animalclass with fieldsspeciesandage, what will be the output of the following code snippet?import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Animal> zoo = new ArrayList<>(); zoo.add(new Animal("Elephant", 10)); zoo.add(new Animal("Tiger", 5)); zoo.add(new Animal("Giraffe", 7)); zoo.clear(); System.out.println(zoo.isEmpty()); } }Answer
true
Explanation: The
clear()method removes all elements from the list, making it empty. TheisEmpty()method returnstrue. -
Given a
Carclass with fieldsmakeandyear, what will be the output of the following code snippet?import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Car> garage = new HashSet<>(); garage.add(new Car("Toyota", 2018)); garage.add(new Car("Honda", 2020)); garage.add(new Car("Ford", 2019)); for (Car car : garage) { if (car.getYear() > 2018) { System.out.print(car.getMake() + " "); } } } }Answer
Honda Ford
Explanation: The loop checks if the car’s year is greater than 2018, so “Honda” and “Ford” are printed since they were manufactured after 2018.
-
Given a
Gadgetclass with fieldsnameandprice, what will be the output of the following code snippet?import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<Gadget> gadgets = new TreeSet<>(new Comparator<Gadget>() { public int compare(Gadget g1, Gadget g2) { return g1.getPrice() - g2.getPrice(); } }); gadgets.add(new Gadget("Smartphone", 700)); gadgets.add(new Gadget("Tablet", 500)); gadgets.add(new Gadget("Laptop", 1000)); System.out.println(gadgets.last().getName()); } }Answer
Laptop
Explanation: The custom comparator sorts the gadgets by price in ascending order, so the last element (highest price) is “Laptop”.
-
Given a
Courseclass with fieldscourseNameandduration, what will be the output of the following code snippet?import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<Course> courses = new LinkedList<>(); courses.add(new Course("Java", 30)); courses.add(new Course("Python", 25)); courses.add(new Course("JavaScript", 20)); courses.removeLast(); System.out.println(courses.getLast().getCourseName()); } }Answer
Python
Explanation: The
removeLast()method removes the last course in the list, leaving “Java” and “Python”. ThegetLast()method then returns the course name of the last remaining course, “Python”.
Tricky MCQs
-
Given a
Developerclass with fieldsnameandexperience, and assumingequalsandhashCodeare correctly overridden, what will be the output of the following code snippet?import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Developer> team = new HashSet<>(); Developer dev1 = new Developer("Alice", 5); Developer dev2 = new Developer("Bob", 3); team.add(dev1); team.add(dev2); dev1.setExperience(6); System.out.println(team.contains(new Developer("Alice", 6))); } }Answer
false
Explanation: Modifying an object in a
HashSetafter it’s been added can lead to unexpected behavior, as the object’s hash code might change, making it difficult to find the object. -
Given an
Employeeclass with fieldsidanddepartment, and assumingequalsandhashCodeare correctly overridden, what will be the output of the following code snippet?import java.util.LinkedHashSet; public class Example { public static void main(String[] args) { LinkedHashSet<Employee> employees = new LinkedHashSet<>(); employees.add(new Employee(1, "HR")); employees.add(new Employee(2, "Finance")); employees.add(new Employee(1, "HR")); employees.add(new Employee(3, "Engineering")); System.out.println(employees.size()); } }Answer
3
Explanation: Since
equalsandhashCodeare overridden, duplicates based on the sameidanddepartmentare not added. So the size is 3. -
Given a
Courseclass with fieldstitleandduration, and assumingCourseimplementsComparable<Course>based ontitle, what will be the output of the following code snippet?import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<Course> courses = new TreeSet<>(); courses.add(new Course("Math", 40)); courses.add(new Course("Science", 35)); courses.add(new Course("Math", 30)); System.out.println(courses.size()); } }Answer
2
Explanation: Since
Courseobjects are compared based ontitle, “Math” is considered a duplicate, and only two unique courses (“Math” and “Science”) are added. -
Given a
Buildingclass with fieldsnameandheight, what will be the output of the following code snippet?import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Building> buildings = new ArrayList<>(); buildings.add(new Building("Empire State", 1250)); buildings.add(new Building("Burj Khalifa", 2717)); buildings.remove(new Building("Empire State", 1250)); System.out.println(buildings.size()); } }Answer
2
Explanation: Without overriding
equalsandhashCode,removedoes not find the object in the list, so the size remains 2. -
Given a
Gadgetclass with fieldsmodelandprice, and assumingequalsandhashCodeare correctly overridden, what will be the output of the following code snippet?import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Gadget> gadgets = new HashSet<>(); gadgets.add(new Gadget("iPhone", 999)); gadgets.add(new Gadget("iPhone", 999)); gadgets.add(new Gadget("Samsung", 899)); gadgets.add(new Gadget("iPhone", 1099)); System.out.println(gadgets.size()); } }Answer
3
Explanation: The first two “iPhone” gadgets are considered duplicates and are not added again, but the third “iPhone” with a different price is added.
-
Given a
Teamclass with fieldsnameandrank, what will be the output of the following code snippet?import java.util.LinkedList; public class Example { public static void main(String[] args) { LinkedList<Team> teams = new LinkedList<>(); teams.add(new Team("Alpha", 1)); teams.add(new Team("Beta", 2)); teams.add(new Team("Gamma", 3)); teams.add(1, new Team("Delta", 4)); System.out.println(teams.get(1).getName()); } }Answer
Delta
Explanation: The
add(1, new Team("Delta", 4))inserts “Delta” at index 1, pushing the other elements to the right. -
Given a
Libraryclass with fieldsnameandbooksCount, and assumingLibraryimplementsComparable<Library>based onbooksCount, what will be the output of the following code snippet?import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<Library> libraries = new TreeSet<>(); libraries.add(new Library("Central", 10000)); libraries.add(new Library("East", 8000)); libraries.add(new Library("West", 12000)); libraries.add(new Library("Central", 10000)); System.out.println(libraries.first().getName()); } }Answer
East
Explanation: The
TreeSetorders libraries bybooksCount, and the one with the smallestbooksCountis “East”. -
Given a
Studentclass with fieldsnameandgrade, and assumingequalsandhashCodeare correctly overridden, what will be the output of the following code snippet?import java.util.HashSet; public class Example { public static void main(String[] args) { HashSet<Student> students = new HashSet<>(); Student s1 = new Student ("John", "A"); Student s2 = new Student("Jane", "B"); students.add(s1); students.add(s2); s1.setGrade("B"); System.out.println(students.contains(new Student("John", "B"))); } }Answer
false
Explanation: Changing
s1’s grade after adding it to the set affects its hash code, making it difficult to find in the set, socontainsreturnsfalse. -
Given a
Countryclass with fieldsnameandpopulation, and assumingequalsandhashCodeare correctly overridden, what will be the output of the following code snippet?import java.util.ArrayList; public class Example { public static void main(String[] args) { ArrayList<Country> countries = new ArrayList<>(); countries.add(new Country("USA", 331000000)); countries.add(new Country("India", 1391000000)); countries.add(new Country("China", 1440000000)); countries.add(1, new Country("Russia", 146000000)); countries.remove(0); System.out.println(countries.get(1).getName()); } }Answer
India
Explanation: “Russia” is added at index 1, pushing “India” to index 2. Removing index 0 removes “USA”, so “India” moves back to index 1.
-
Given a
Productclass with fieldsnameandprice, and assumingProductimplementsComparable<Product>based onprice, what will be the output of the following code snippet?import java.util.TreeSet; public class Example { public static void main(String[] args) { TreeSet<Product> products = new TreeSet<>(); products.add(new Product("Phone", 700)); products.add(new Product("Tablet", 500)); products.add(new Product("Laptop", 1200)); System.out.println(products.pollFirst().getName()); } }Answer
Tablet
Explanation: The
TreeSetorders products byprice, andpollFirst()retrieves and removes the lowest-priced product, which is “Tablet”.