HashMap遍历, ArrayList实现不重复数据的存储

总结一些HashMap和ArrayList的知识点,老是忘记。

HashMap

HashMap用来存储<key, value>键值对,需要注意的是,key值唯一,若put()操作中key值出现了重复,那么后一个键值对将覆盖前一个key值相同的键值对。

HashMap<Integer, Integer>dif=new HashMap<>();
dif.put(1,3);
dif.put(1,4);

dif中只有(1,4)键值对。

HashMap的遍历操作

HashMap的遍历需要使用迭代器进行操作,迭代器通过set来获取。

HashMap<Integer, Integer>dif=new HashMap<>();
dif.put(1,3);
dif.put(1,4);
Set<HashMap.Entry<Integer, Integer>>set=dif.entrySet();
Iterator<HashMap.Entry<Integer, Integer>> it=set.iterator();
while(it.hasNext()){
    HashMap.Entry<Integer, Integer> entry=it.next();
    int x=entry.getKey();
    int y=entry.getValue();
    System.out.println("x= "+x+",  y= "+y);
}

ArrayList

当数组长度不固定时,可以使用ArrayList来进行操作。

ArrayList根据下标取数

之前把ArrayList和数组弄混了,像数组一样直接用a[i]这种方式取数。这是错误的,ArrayList中不能这样使用。正确方式应该使用get()方法,如下:

ArrayList<String> list= new ArrayList<>();
list.add("cit");
list.add("cig");
String x=list.get(1);

ArrayList判断数组中是否存在某个数

ArrayList可以用来判断数组中是否存在某个数,利用contains()方法即可,如果存在返回true,否则返回false。

System.out.println(list.contains("fig"));

ArrayList,String, 数组获取长度的方法比较

1 ArrayList

System.out.println(list.size());

2 String

String x="test";
System.out.println(x.length());

3 数组

int []a={1,5,3};
System.out.println(a.length);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值