Collection:单列(接口)
分类:常用(使用的时候需要使用以下实现类)
List接口:可以重复
ArrayList:
LinkedList:
Set接口:不可以重复
HashSet:
TreeSet:
Map接口:有两列
HashMap
常用方法:
add():添加元素
remove():从项目中将元素移除
clear():将元素清空
isEmpty():判断集合是否为空
size();集合长度
contains():是否包含某元素
遍历集合:
可以通过迭代器来遍历集合 Iterator<E> iterator();返回集合中的元素
也可以使用增强for来输出数据
常用方法:Next():返回下一个
hasNext():如果存在更多则返回true
代码:
public static void main(String[] args) { Collection<String> collection = new ArrayList<>(); collection.add("a"); collection.add("b"); Iterator<String> i=collection.iterator(); while (i.hasNext()){ String next = i.next(); System.out.println(next); } }
List
特点:有序集合,可以重复
Set
特点:不可以重复
比较器:可以通过比较器Comparator来进行排序,元素重复时不使用会报错
要么在类中重写compareTo要么在实例化对象时重写
代码例子:
//region TreeSet Set<Student> treeSet = new TreeSet<>(new Comparator<Student>() { @Override public int compare(Student s1, Student s2) { int num=s1.getAge()-s2.getAge(); int num2=num==0?s1.getName().compareTo(s2.getName()):num; return num2; } }); // Set<Student> treeSet = new TreeSet<>(); Student student1 = new Student(23,"豹子"); Student student = new Student(23,"奥兹"); treeSet.add(student1); treeSet.add(student); treeSet.forEach(ss-> System.out.println(ss.getAge()+","+ss.getName())); //endregion
Map
特点:成对出现,参数的类型需要一致
常用操作:
keyset:获取所有键
get:获取键所对应的值
entrySet:获取所有的键值对象
代码示例:
//region Map Map<String, Student> studentMap = new HashMap<String,Student>(); Student sss = new Student(5, "大宝"); Student ssss = new Student(7, "二宝"); studentMap.put("一楼",sss); studentMap.put("二楼",ssss); //通过键获取对象 Set<String> keySet = studentMap.keySet(); for (String s1 :keySet){ Student student2 = studentMap.get(s1); System.out.println(s1+","+student2.getAge()+","+student2.getName()); } //通过键值对象获取键、值 System.out.println("————————————————"); Set<Map.Entry<String, Student>> entrySet = studentMap.entrySet(); for (Map.Entry<String, Student> ens:entrySet){ String key = ens.getKey(); Student value = ens.getValue(); System.out.println(key+","+value.getAge()+","+value.getName()); } //endregion