java中,List,ArrayList,Map集合的使用?

java中,List,ArrayList,Map集合的使用? 


Cats萌萌
浏览 1553回答 4
4回答

Helenr

List是接口,它存放的数据是有序,会确保以一定的顺序保存元素,使用是使用它的实例类,如ArrayList,LinkedList;如List<String> list=new ArrayList<>();ArrayList是List的一个实例类,使用ArrayList可以顺序存放数据;如:List<String> list=new ArrayList<>(); list.add("test");获取数据:for(int i=0;i<list.size();i++){String str=list.get(i);}Map 是集合,是按键值对(key-value)存放数据, 使用时,使用Map的使用类HashMap<>,如Map<String,String> map=new HashMap<String,String>(); map.put("id","100000001");map.put("name","张三");获取数据:1、直接遍历for (String key : map.keySet()) {System.out.println("key= " + key + " and value= " +map.get(key));}2、Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();while (it.hasNext()) {Map.Entry<String, String> entry = it.next();System.out.println("key= " + entry.getKey() + " and value= "+ entry.getValue());}

青春有我

list和arrayList是对列表的处理,列表内容可以重复map是对关系映射的处理,内容不可重复

30秒到达战场

你首先要了解什么是Map,可以理解为Map是一堆key和value的映射集合(或者说一堆键值对的集合)。12345678List&nbsp;list&nbsp;=&nbsp;new&nbsp;ArrayList();Map&nbsp;map&nbsp;=&nbsp;new&nbsp;HashMap();&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;list.add("a");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;list.add("c");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;list.add("b");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for(int&nbsp;i&nbsp;=0;i<list.size();i++){&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;map.put(i,&nbsp;list.get(i));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}然后你要用Map里的东西,可以使用map.get(1)这种形式获取,他和list.get(1); 相等都为“c”。另外建议初始化Map和List的时候,定义好所存的数据类型。List<String> list = new ArrayList<String>();Map<Integer, String> map = new HashMap<Integer, String>();
打开App,查看更多内容
随时随地看视频慕课网APP