Java中有很多有序集合类型可供选择,如ArrayList、LinkedList、TreeSet、LinkedHashSet、PriorityQueue等。每个集合都有它自己的特点,可以根据具体业务场景需求选取适合的集合。这篇文章将从多个方面对Java有序集合进行详细介绍和使用。
一、ArrayList
ArrayList是Java中常用的集合之一,其内部基于数组实现,可以动态增长,同时支持随机访问。以下是ArrayList的简单应用示例:
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("World");
list.add("Java");
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
list.remove(1);
for (String str : list) {
System.out.println(str);
}
上面的代码创建了一个String类型的ArrayList,并添加了3个元素。使用for循环和get方法遍历ArrayList并输出其内容,再使用remove方法删掉第二个元素,最后使用增强型for循环遍历ArrayList并输出其内容。
二、LinkedList
LinkedList是Java中另一个常用的集合,其内部基于链表实现,支持动态增长和双向访问。以下是LinkedList的简单应用示例:
LinkedList<Integer> list = new LinkedList<>();
list.add(1);
list.add(3);
list.add(5);
for (int num : list) {
System.out.println(num);
}
list.removeLast();
for (int num : list) {
System.out.println(num);
}
上面的代码创建了一个Integer类型的LinkedList,并添加了3个元素。使用增强型for循环遍历LinkedList并输出其内容,再使用removeLast方法删除最后一个元素,并使用增强型for循环遍历LinkedList并输出其内容。
三、TreeSet
TreeSet是Java中一个支持自然排序的有序Set集合,内部使用红黑树实现。以下是TreeSet的简单应用示例:
TreeSet<Integer> set = new TreeSet<>();
set.add(2);
set.add(4);
set.add(1);
for (int num : set) {
System.out.println(num);
}
set.remove(4);
for (int num : set) {
System.out.println(num);
}
上面的代码创建了一个Integer类型的TreeSet,并添加了3个元素。使用增强型for循环遍历TreeSet并输出其内容,再使用remove方法删除元素4,并使用增强型for循环遍历TreeSet并输出其内容。
四、LinkedHashSet
LinkedHashSet是Java中的有序Set集合,内部使用哈希表与链表实现。与TreeSet不同的是,LinkedHashSet保持元素插入的顺序,而不关心元素的大小顺序。以下是LinkedHashSet的简单应用示例:
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("W");
set.add("H");
set.add("J");
for (String str : set) {
System.out.println(str);
}
set.remove("H");
for (String str : set) {
System.out.println(str);
}
上面的代码创建了一个String类型的LinkedHashSet,并添加了3个元素。使用增强型for循环遍历LinkedHashSet并输出其内容,再使用remove方法删除元素”H”,并使用增强型for循环遍历LinkedHashSet并输出其内容。
五、PriorityQueue
PriorityQueue是Java中的一个优先队列,其内部使用堆来实现。可以保证每次出队的元素都是优先级最高的,也可以指定比较器实现自定义排序规则。以下是PriorityQueue的简单应用示例:
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.offer(3);
queue.offer(5);
queue.offer(1);
while (!queue.isEmpty()) {
System.out.println(queue.poll());
}
PriorityQueue<String> strQueue = new PriorityQueue<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
strQueue.offer("Hello");
strQueue.offer("World");
strQueue.offer("Java");
while (!strQueue.isEmpty()) {
System.out.println(strQueue.poll());
}
上面的代码创建了一个Integer类型的PriorityQueue,并添加了3个元素。使用while循环和poll方法遍历PriorityQueue并输出其内容,输出的结果是1、3、5。接着,创建了一个String类型的PriorityQueue,并使用自定义的Comparator实现了倒序排序,再使用while循环和poll方法遍历PriorityQueue并输出其内容,输出的结果是World、Java、Hello。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/297526.html
微信扫一扫
支付宝扫一扫