• 集合分为两大接口 Collection 和 Map

【java】集合相关、配合理解泛型
【java】集合相关、配合理解泛型

  • Collection接口 :List Queue Set
  • 常用的Collection的实现类
    ArrayList 实现 List
    LinkedList 实现 List和Queue
    HashSet 实现 Set
  • 常用的Map实现类
    HashMap
  • Set的遍历
//不使用泛型
Set set = new HashSet();
		set.add(taidi);
		set.add(xuenarui);
		Iterator it = set.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
//在集合中查找泰迪的信息
boolean flag = false;
Iterator it = set.iterator();
while (it.hasNext()) {
	//不使用泛型的时候需要对对象进行强制转换,因为next()方法返回的是一个不定类型,需要new的时候自己决定
	Cat c = (Cat)it.next();
	// next()返回的类型不确定,可以任意指定,下面的语句编译不会报错, 但是运行时会报错,这样的代码是不安全的
	String c = (String)it.next();
	if (c.getName().equal("taidi")) flag = true;
	break;
}
//使用泛型
Set<Dog> set = new HashSet<Dog>();
		set.add(taidi);
		set.add(xuenarui);
		Iterator<Dag> it = set.iterator();
		while (it.hasNext()) {
			System.out.println(it.next());
		}
//使用泛型后的集合查找信息
boolean flag = false;
// 使用泛型限制迭代器里的类型
Iterator<Dog> it = set.iterator();
Cat c = null;
it = set.iterator();
while (it.hasNext()) {
	// 不用进行强制转换
	c = it.next();
	// 下面语句编译时会报错,代码安全
	String c = (String)it.next();
	if (c.getName().equals("taidi")) {
		flag = true;
		break;
	}
}
  • 阿里巴巴设计规约禁止在遍历集合的时候删除集合,因为删除的那一刻会改变集合的数据内存地址分布,是不安全的。解决办法可以是先把要删除的集合元素存进新的集合1里,再使用removeAll(集合1)进行删除。
Set<Dog> tempSet = new HashSet<Dog>();
// 遍历一个set集合
for (Dog dog : set) {
	if (set.getName.contains("a")) tempSet.add(dog);
}
set.remoceAll(tempSet);
  • Map没有继承Iterable<>,但是Map内定义了个静态的实现接口Map.Entry的成员,Entry用来映射键值对的集合,其中entrySet()可以将Map的所有元素的键值对组装成一个Set返回,对于这个Set也就有了Iterable<>的方法。

相关文章:

  • 2021-08-26
  • 2021-06-22
  • 2021-07-11
  • 2021-09-27
  • 2022-02-06
猜你喜欢
  • 2022-12-23
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2021-10-08
  • 2021-11-13
  • 2022-02-05
相关资源
相似解决方案