赞
踩
提示:以下是本篇文章正文内容,下面案例可供参考
①增加
②删除 map.remove()
③.修改
map集合的底层是set集合,没有下标,map集合的键是唯一,
④查找
key是可以为空的
①keySet (先获得map集合所有的key)
②entrySet
map集合的映射关系,set里放的是关系
代码如下(示例):
- public class One2 {
- public static void main(String[] args) {
- String a="aksdjhfeirusiduyfydsskdoeuyftdtsvcssdssasrpouxsawklm";
- char[] chars = a.toCharArray();
- Map<Character, Integer> map=new HashMap<Character, Integer>();
- for (char c : chars) {
- Integer count=map.get(c);
- if(count==null||count==0) {
- map.put(c, 1);
- }else {
- map.put(c,count+1);
- }
- }
- Set<Entry<Character, Integer>> entrySet = map.entrySet();
- for (Entry<Character, Integer> entry : entrySet) {
- System.out.println(entry.getKey()+"出现了"+entry.getValue()+"次");
- }
-
-
- }
- }
运行结果:
思路:1.字符串转换成字符数组
2.遍历数组,将字符放入map集合中key
3.判断如果字符没有,那么就给字符对应的值设置为1,如果有就给对应的值+1
错误:(Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer)String不能转换成Integer
如果我把Object改为Integer (在编译期就会报错),所以说,泛型最大的好处在于将运行时的异常转换成编译期的错误
正确代码如下(示例):
- public class One3 {
- public static void main(String[] args) {
- Map<String,Integer> map=new HashMap<>();
- map.put("就是就是", 1);
- map.put("薛之谦", 2);
- map.put("带小妹", 3);
- map.put("赵丽颖", 4);
- map.put("杨洋", 5);
- //刷选出value为偶数对应的key
- Set<Entry<String,Integer>> entrySet = map.entrySet();
- for (Entry<String, Integer> entry : entrySet) {
- Object value = entry.getValue();
- Integer val=(Integer)value;
- if(val%2==0) {
- System.out.println("偶数对应的key为: "+entry.getKey());
- }
- }
- }
-
- }

1.Collections排序
代码如下(示例):
- public class One4 {
- public static void main(String[] args) {
- List<user> list=new ArrayList<>();
- list.add(new user("景甜",1234));
- list.add(new user("张一龙",19000));
- list.add(new user("迪丽热巴",10004));
- list.add(new user("书架",678));
- list.add(new user("甜",1874));
-
- Collections.sort(list, new Comparator<user>() {
- @Override
- public int compare(user o1, user o2) {
- // TODO Auto-generated method stub
- return o1.getMoney()-o2.getMoney();
- }
- });
-
-
- for (Object object : list) {
- System.out.println(object);
- }
-
-
- }
-
- }
-
-
- class user {
- private String name;
- private int money;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
-
- public int getMoney() {
- return money;
- }
- public void setMoney(int money) {
- this.money = money;
- }
- public user() {
- // TODO Auto-generated constructor stub
- }
-
-
- public user(String name, int money) {
- super();
- this.name = name;
- this.money = money;
- }
- @Override
- public String toString() {
- return "user [name=" + name + ", money=" + money + "]";
- }
-
-
-
-
-
- }

①.Arrays.toString()
这样结果会输出一串地址
而用Arrays.toString 不一样
②.asList (将数组变成集合来操作,不能违背数组本身的特点)
错误示例:
③.sort (从小到大排序)
该处使用的url网络请求的数据。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。