Java通识基础25——集合类2
Map根接口
特征——每一个元素都有Key和Value二者互相绑定——名为Entry(条目)
key和value存在单向的一对一的关系(好比地址和参数)
特征
key不能重复(如果第二次放入的key等于前者,那么前者会被覆盖)key是无序的
所以:Set的集合元素和Map对key的要求是完全一样的
实际:如果将Map的Value当做空来处理,Map只有key——这些key元素组成了 Set集合
(可见和Set集合基本一致)
所以,Java的Set集合基本都是靠Map集合来实现——将Map的value看做空,只实现key部分
Map集合类的size是其中条目的数量- 添加条目的方法为
put,语法和add相同,只不过要传入key,value两个形参 - 一切方法都与
key绑定,如get,remove等都是传入key - 注意:
Map不能用foreach来遍历,甚至不能直接用iterator来遍历
但是可以改为对Map的所有key进行遍历
HashMap实现类的特征与功能(基本等同与HashSet)
import java.util.HashMap;import java.util.Map;public class HashMapTest {public static void main(String[] args) {Map<Apple,String>map=new HashMap<>();map.put(new Apple("Red",1.2),"well");map.put(new Apple("Red",1.2),"well");map.put(new Apple("DarkRed",1.8),"very well");map.put(new Apple("Black",0.2),"fuck");System.out.println(map);}}class Apple{private final String color;private final double weight;public Apple(String color,Double weight){this.color=color;this.weight=weight;}@Overridepublic String toString(){return "Apple[color"+this.color+","+"weight"+this.weight;}@Overridepublic boolean equals(Object obj){if (this==obj){return true;}if(obj!=null&&obj.getClass()==Apple.class){Apple target=(Apple)obj;return this.color.equals(target.color)&&(this.weight-target.weight<1e-6);}return false;}@Overridepublic int hashCode(){return this.color.hashCode()*31+(int)this.weight;}}/*{Apple[colorRed,weight1.2=well, Apple[colorDarkRed,weight1.8=very well, Apple[colorBlack,weight0.2=fuck}*/
掌握几个方法重写
Properties子类
接口HashTapble已经被HashMap取代了
Properties特性:可以非常方便的读写属性文件
- 继承了
HashTapble,本质上是Map结构,但其key\value都是String类型的,所以不需要指定泛型
import java.util.Properties;public class PropertiesTest {public static void main(String[] args){Properties p1=new Properties();p1.put("wyd","233");p1.put("cxd","233");p1.put("gtn","233");System.out.println(p1);}}
