温馨提示×

java如何定义集合

小亿
94
2024-01-19 03:15:58
栏目: 编程语言

在Java中,有多种方式可以定义集合,最常用的是使用Java集合框架中的接口和类。

  1. 使用List接口定义一个列表:
List<String> list = new ArrayList<>();
  1. 使用Set接口定义一个集:
Set<Integer> set = new HashSet<>();
  1. 使用Map接口定义一个映射:
Map<String, Integer> map = new HashMap<>();
  1. 使用Queue接口定义一个队列:
Queue<String> queue = new LinkedList<>();
  1. 使用Stack类定义一个栈:
Stack<Integer> stack = new Stack<>();

除了上述方式,还可以使用其他的集合类来定义集合,如Vector、LinkedList等。例如:

Vector<String> vector = new Vector<>();
LinkedList<Integer> linkedList = new LinkedList<>();

需要注意的是,上述代码中的<>中的类型参数可以根据具体需求进行替换。

0