• Home
  • LLMs
  • Python
  • Docker
  • Kubernetes
  • Java
  • Maven
  • All
  • About
Java | LinkedList
  1. Notes
  2. Example
  3. Iterator
  4. ListIterator
  5. binarySearch

  1. Notes
    Ordered collection
    null elements allowed
    Duplicates elements allowed
  2. Example
    LinkedList<String> ls = new LinkedList<>();
    
    ls.add(null);
    ls.add("ccc");
    ls.add("bbb");
    ls.add("bbb");
    ls.add("aaa");
    ls.add("aaa");
    ls.add("aaa");
    
    ls.forEach(System.out::println);
    Output:
    null
    ccc
    bbb
    bbb
    aaa
    aaa
    aaa
  3. Iterator
    LinkedList<String> ls = new LinkedList<>();
    
    ls.add("ccc");
    ls.add("bbb");
    ls.add("aaa");
    
    Iterator<String> i = ls.iterator();
    
    if (i.hasNext())
        i.next();
    
    i.remove(); // removes the last element returned: ccc
    
    ls.forEach(System.out::println);
    Output:
    bbb
    aaa
  4. ListIterator
    LinkedList<String> ls = new LinkedList<>();
    
    ls.add("ccc");
    ls.add("bbb");
    ls.add("aaa");
    
    ListIterator<String> li = ls.listIterator();
    ListIterator<String> li_copy = ls.listIterator();
    
    if (li.hasNext())
        li.next();
    
    li.set("zzz"); // this will replace the value "ccc"
    li_copy.next(); // OK
    
    li.add("eee");
    // li_copy.next(); // this will throw java.util.ConcurrentModificationException
    
    ls.forEach(System.out::println);
    Output:
    zzz
    eee
    bbb
    aaa
  5. binarySearch
    LinkedList<String> ls = new LinkedList<>();
    
    ls.add("c");
    ls.add("bb");
    ls.add("aaa");
    
    Collections.sort(ls); // Objects must implement java.lang.Comparable<T> (Compiler error)
    System.out.println(Collections.binarySearch(ls, "aaa")); // Objects must implement java.lang.Comparable<T> (Compiler error)
    
    Collections.sort(ls, Comparator.comparing(String::length));
    System.out.println(Collections.binarySearch(ls, "aaa", Comparator.comparing(String::length)));
    Output:
    0
    2
© 2025  mtitek