Created
October 12, 2022 14:18
-
-
Save rmg007/b1fa1d4c51fea63ffeb39211fa196bf1 to your computer and use it in GitHub Desktop.
Finding and Accessing elements in a List
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.ArrayList; | |
| import java.util.List; | |
| public class FindingElementInList { | |
| public static void main(String[] args) { | |
| List<Integer> list1 = new ArrayList<>(List.of(6, 1, 2, 3, 4, 5, 6)); | |
| List<Integer> list2 = new ArrayList<>(List.of(1, 2, 3)); | |
| // output: contains 1: true | |
| System.out.println("contains 1: " + list1.contains(1)); | |
| /* | |
| output: list1 contains list2: true | |
| Note: use HashSet if you want to check only unique elements | |
| System.out.println(new HashSet<>(list1).containsAll(list2)); | |
| */ | |
| System.out.println("list1 contains list2: " + list1.containsAll(list2)); | |
| // this prints false because obviously list2 doesn't contain all elements in list1 | |
| System.out.println(list2.contains(list1)); | |
| //output: first index of 6: 0 | |
| System.out.println("first index of 6: " + list1.indexOf(6)); | |
| // prints -1 because list1 doesn't contain 99 | |
| System.out.println(list1.indexOf(99)); | |
| // lastIndexOf will search the list from end to the back | |
| // output: last index of 6: 6 | |
| System.out.println("last index of 6: " + list1.lastIndexOf(6)); | |
| // Output: the element at index 2 is: 3 | |
| System.out.println("the element at index 2 is: " + list2.get(2)); | |
| // list 2 has only 3 element and the last index is 2 | |
| // this line throws IndexOutOfBoundsException as index 8 is out of bounds | |
| //System.out.println(list2.get(8)); | |
| System.out.println(list1.isEmpty()); // false | |
| System.out.println(list1.size()); // 7 | |
| list1.clear(); // emptying list | |
| System.out.println(list1.isEmpty()); // true | |
| System.out.println(list1.size()); // 0 | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment