数组和集合相关的函数和方法调用
数组和集合是常用的数据结构,在编程中经常会使用到它们。下面是一些常用的数组和集合相关的函数和方法调用。
一、数组的常用方法调用:
1. 创建数组:
- 使用字面量创建数组:int[] array = {1, 2, 3, 4, 5};
- 使用new关键字创建指定长度的数组:int[] array = new int[5];
- 多维数组的创建:int[][] array = new int[3][3];
2. 获取数组长度:int length = array.length;
3. 访问数组元素:
- 通过索引访问:int element = array[index];
- 修改数组元素:array[index] = newValue;
4. 遍历数组:
- 使用普通for循环遍历:for (int i = 0; i < array.length; i++) { }
- 使用增强for循环遍历:for (int element : array) { }
5. 数组的排序:
- 使用Arrays.sort()方法进行排序:Arrays.sort(array);
- 自定义排序规则,实现Comparator接口,并使用Arrays.sort()方法:Arrays.sort(array, comparator);
6. 数组的查找:
- 使用Arrays.binarySearch()方法进行二分查找:int index = Arrays.binarySearch(array, key);
- 自定义查找规则,实现Comparator接口,并使用Arrays.binarySearch()方法:int index = Arrays.binarySearch(array, key, comparator);
7. 数组的拷贝:
- 使用System.arraycopy()方法进行拷贝:System.arraycopy(sourceArray, sourceStart, destinationArray, destinationStart, length);
- 使用Arrays.copyOf()方法进行拷贝:int[] newArray = Arrays.copyOf(array, length);
二、集合的常用方法调用:
1. 创建集合:
- 使用ArrayList类创建动态数组:List<Integer> list = new ArrayList<>();
- 使用HashSet类创建无序集合:Set<Integer> set = new HashSet<>();
- 使用HashMap类创建键值对映射: Map<String, Integer> map = new HashMap<>();
2. 添加元素:
- 使用add()方法添加元素到集合: list.add(element);
- 使用put()方法添加键值对到映射: map.put(key, value);
3. 删除元素:
- 使用remove()方法删除集合中的指定元素: list.remove(element);
- 使用remove()方法删除映射中的指定键: map.remove(key);
4. 获取集合大小:
- 使用size()方法获取集合的大小: int size = list.size();
5. 遍历集合:
- 使用普通for循环遍历: for (int i = 0; i < list.size(); i++) { }
- 使用增强for循环遍历: for (int element : list) { }
- 使用Iterator迭代器遍历:
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
int element = iterator.next();
}
6. 集合的排序:
- 使用Collections.sort()方法进行排序: Collections.sort(list);
- 自定义排序规则,实现Comparator接口,并使用Collections.sort()方法: Collections.sort(list, comparator);
7. 集合的查找:
- 使用contains()方法判断集合是否包含指定元素: boolean contains = list.contains(element);
- 使用containsKey()方法判断映射是否包含指定键: boolean containsKey = map.containsKey(key);
8. 集合的拷贝:
- 使用ArrayList构造方法进行拷贝: List<Integer> newList = new ArrayList<>(list);
- 使用HashSet构造方法进行拷贝: Set<Integer> newSet = new HashSet<>(set);
以上是一些常用的数组和集合相关的函数和方法调用,希望能对你有所帮助。
