总结一些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);