public class List { public static void main(String[] args) { var list = new ArrayList(); } }
public class List { public static void main(String[] args) { var list = new ArrayList(); list.add("a"); list.add(1); list.add(1); System.out.println(list); } }
public class List { public static void main(String[] args) { var list = new ArrayList(); list.add("a"); list.add(1); list.add(1); System.out.println(list); list.clear(); System.out.println(list); } }
public class List { public static void main(String[] args) { var list = new ArrayList(); list.add("a"); list.add(1); list.add(1); System.out.println(list); list.set(2, "a"); System.out.println(list); } }
public class Set { public static void main(String[] args) { var set = new HashSet<>(); } }
Add data to the collection:
add()
The elements in the collection cannot be repeated
public class Set { public static void main(String[] args) { var set = new HashSet<>(); set.add(1); set.add("a"); set.add("a"); System.out.println(set); } }
Clear the collection data:
clear()
public class Set { public static void main(String[] args) { var set = new HashSet<>(); set.add(1); set.add("a"); set.add("a"); System.out.println(set); set.clear(); System.out.println(set); } }
Delete the specified element
public class Set { public static void main(String[] args) { var set = new HashSet<>(); set.add(1); set.add("a"); set.add("a"); System.out.println(set); set.remove("a"); System.out.println(set); } }
The difference between ArrayList and HashSet
2. ArrayList is repeatable and ordered: high query efficiency, additions and deletions Inefficient and lightweight thread unsafe. Arraylist: Not fast at inserting and deleting data, but faster at random extraction
Generic
Generally, generics are used when using collections. Generics are to add a type constraint to the collection. It can be String or Object. Generics do not support the basic type int. Please use the wrapper type Integer
to create a generic:
List<String> list = new ArrayList<>();
In this way, only String types can be added to this collection.
The above is the detailed content of How to use ArrayList and HashSet in Java Collection. For more information, please follow other related articles on the PHP Chinese website!