banner
Onei

Onei

github
nintendo switch
discord server
steam
pixiv
bento
follow

Gathering or assembly

🗃️ Collection#

Some Methods#

  • add()
  • addAll()
  • remove()
  • removeAll()
  • clear()
  • isEmpty()
  • contains()

contains and remove both call the equals method

If the collection contains primitive data types, they must be boxed into their corresponding wrapper classes.

No methods for modification or querying are provided

class-and-interface-hierarchy

🔍 iterator#

Iterator

Mainly used for traversal operations. Using an iterator can shield the differences between data structures.

  • hasNext()
  • next()
  • remove()

Once an iterator is generated, the collection cannot be modified. If modification is needed, a new iterator must be generated.

Enhanced for Loop#

A shorthand for iterators. It also cannot be used for deletion.

🐾 List#

Ordered and can contain duplicates.

ArrayList#

Underlying data structure is an Object array. Efficient for querying and modification.

  • add(index,items)
  • set(index,items)
  • size()

LinkedList#

Underlying data structure is a doubly linked list. Efficient for random insertion and deletion.

  • add(index,items)
  • set(index,items)
  • size()

🍊 Set#

Unordered (does not guarantee the order of adding and retrieving data).
Cannot contain duplicates (will not add duplicates).

TreeSet#

Underlying data structure is TreeMap.

TreeMap is based on a red-black tree. The added elements will be automatically sorted in a certain format.

The data added to TreeMap must have a comparator.

Therefore, if we want to add objects without a comparator or custom objects, an error will occur. In addition, because sorting requires comparison, only data of the same type can be added.

  • Numbers: ascending order by size
  • Strings: ASCII code for each character
  • Date: natural date

HashSet#

The K part of HashMap is used as the underlying data structure.

HashMap is based on a hash table.

🤼‍♀️ Comparable#

Comparator. Elements added to a TreeSet need to implement the Comparable interface and override the compareTo() method in the interface.
The compareTo() method returns a value that represents the sorting rule.
When adding elements, the compareTo() method of the element object in the collection is called to compare with the elements in the collection.
If ==0, it means it is a duplicate and will not be added.
If <0, it means the element to be added is smaller and will be placed before.
If >0, it means the element to be added is larger and will be placed after.

import java.util.TreeSet;

public class Tree {
  public static void main(String[] args) {
    TreeSet<Object> tree = new TreeSet<>();
    tree.add(new User("张三",18));
    tree.add(new User("李四",13));
    tree.add(new User("王五",32));
    tree.add(new User("赵六",11));
    System.out.println(tree);
  }
}

class User implements Comparable {
  private String name;
  private int age;

  public User() {
  }

  public User(String name, int age) {
    this.name = name;
    this.age = age;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getAge() {
    return age;
  }

  public void setAge(int age) {
    this.age = age;
  }

  @Override
  public String toString() {
    return "User [name=" + name + ", age=" + age + "]";
  }

  @Override
  public int compareTo(Object o) {
    if (o instanceof User) {
      User u = (User) o;
      // this.getAge() - u.getAge() is greater than 1 for ascending order sorting
      return this.getAge() - u.getAge();
    }
    return 0;
  }
}

🍭 Comparator#

Comparator class. The elements to be added do not need to implement this interface.

The Integer class has a default ascending comparison method. If you want descending order, you can redefine the sorting rule by implementing the Comparator interface; or when saving objects that cannot be sorted (not implementing the Comparable interface) in a TreeSet, you still need a Comparator for comparison.
When the saved elements cannot be sorted (not implementing the Comparable interface) or the sorting rule does not meet our requirements, the Comparator interface can be implemented and the compare() method can be overridden for sorting.

When both the Comparator comparator and the Comparable comparator exist, the Comparator has a higher priority than the Comparable.

This demonstrates the principle of closed for modification, open for extension.

Used with Anonymous Classes#

import java.util.Comparator;
import java.util.TreeSet;

@SuppressWarnings("all")
public class UnNamed {
  public static void main(String[] args) {
    // TreeSet<Object> tree = new TreeSet<>(new MyComparator());
    // Anonymous class, commonly used in comparators
    TreeSet<Object> tree = new TreeSet<>(new Comparator() {
      @Override
      public int compare(Object o1, Object o2) {
        if (o1 instanceof Integer && o2 instanceof Integer) {
          // o1 is the element to be added
          // System.out.println(o1);
          // o2 is the element in the collection
          // System.out.println(o2);

          Integer i1 = (Integer) o1;
          Integer i2 = (Integer) o2;
          // 10-9 for descending order sorting
          return i2 - i1;
        }
        return 0;
      }
    });
    tree.add(11);
    tree.add(7611);
    tree.add(1);
    tree.add(100);
    tree.add(660);
    tree.add(98);
    System.out.println(tree);
  }
}

class MyComparator implements Comparator {
  @Override
  public int compare(Object o1, Object o2) {
    if (o1 instanceof Integer && o2 instanceof Integer) {
      // o1 is the element to be added
      // System.out.println(o1);
      // o2 is the element in the collection
      // System.out.println(o2);

      Integer i1 = (Integer) o1;
      Integer i2 = (Integer) o2;
      // 10-9 for descending order sorting
      return i2 - i1;
    }
    return 0;
  }
}

〽️ List Sorting#

Collections.sort(list) sorting method
void sort(Comparator<? super E> c) can also pass in a Comparator object to use the sorting method of List

🔗 Hash Table#

Used to store key-value mapping relationships. The storage method is an array that saves linked lists to solve hash collision problems.
The linked list node contains four attributes:

  • Hash value
  • Key
  • Value
  • Next pointer

Hash Table

✔️ Generics#

Type checking

Without using generics, the collection can store data of any type, and the data will be cast to the Object type.
Disadvantage: When retrieving, you will get data of type Object, and when using object-specific attributes, you need to perform a type cast (downcast).

After using generics, the collection can only store data of a single type.
Advantage: Because the type of the saved data is consistent, there is no need to perform a downcast when using it.
Disadvantage: Can only store data of a single type, and the passed generic type can only be a reference type, not a primitive type.

public class Generic {
	public static void main(String[] args) {
		MyClass myClass = new MyClass();
		myClass.method(1);
		myClass.method("xx");
		MyClass<String> mm = new MyClass<String>();
		mm.m1("xxx");
		// mm.m1(123);
	}
}

// If the generic type is not passed when setting the generic, the default is Object type
class MyClass<T> {
	public void method(T obj) {
		System.out.println(obj);
	}
}
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.