java进阶(4)集合类:ArrayList和 LinkedList,Vector 和stack,HashMap的基本用法

时间:2022-08-09 16:59:03
import java.util.*;
import java.io.*;
public class Test2{
public static void main(String[]args)throws Exception{
//1.ArrayList和 LinkedList用法差不多
/* 1. LinkedList bb=new LinkedList();
Sp sp1=new Sp("001","话梅",5f);
Sp sp2=new Sp("002","薯片",2f);

bb.addFirst(sp1);//First 的作用是:后进先出,先放进去的在最里面,后放进去的在最外面
bb.addFirst(sp2);

for(int i=0;i<bb.size();i++)
{
System.out.println(((Sp)bb.get(i)).getMingcheng());
//普通取法

//System.out.println(((Sp)bb.getFist(i)).getMingcheng());
//从第一个开始输出,然后循环后又从第一个输出

//System.out.println(((Sp)bb.getLast(i)).getMingcheng());
//从最后一个输出,然后循环后又从最后一个输出

}
*/
//2.Vector 和stack可以处理重复问题:如果出现一样的可以直接忽略掉
/*2.
Vector cc=new Vector();
Sp sp1=new Sp("001","巧克力",20f);
Sp sp2=new Sp("002","果浦",10f);

cc.add(sp1);
cc.add(sp2);
for(int i=0;i<cc.size();i++){
System.out.println(((Sp)cc.get(i)).getMingcheng());
}
}
*/
//3.HashMap的格式不太一样,而且不能够循环输出,只能输单值
/*3.
Sp sp1=new Sp("001","巧克力",20f);
Sp sp2=new Sp("002","果浦",10f);

ee.put("001",sp1);//HashMap不用add方法,用put
ee.put("002",sp2);//后面是两个参数,键值的意思
if(ee.containsKey("002"))//不需要遍历,直接调用containsKey()方法
{
System.out.println("该食品的信息为:");
Sp sp=(Sp)ee.get("002");
System.out.println(sp.getMingcheng());
System.out.println(sp.getJiage());
}else{
System.out.println("对不起,没有该食品。");
}
}

*/
//4.若需遍历则加用Iterator
HashMap ee=new HashMap();
Sp sp1=new Sp("001","巧克力",20f);
Sp sp2=new Sp("002","果浦",10f);

ee.put("001",sp1);//HashMap不用add方法,用put
ee.put("002",sp2);//后面是两个参数,键值的意思
Iterator it=ee.keySet().iterator();
/*
* 把里面的所有的键值进行激活
* 相当于for循环
*/

while(it.hasNext())
//还有没有下一个,如果有就为真,返回为true和false

{
String key=it.next().toString();
//next()接下一个键值,toString()用这个方法把它的转化成字符串
Sp sp=(Sp)ee.get(key);
System.out.println("食品名称:"+Sp.getMingcheng());
}
}
class Sp{
private String bianhao;
private String mingcheng;
private float jiage;
Sp(String bianhao,String mingcheng,float jiage){
this.bianhao=bianhao;
this.mingcheng=mingcheng;
this.jiage=jiage;
}
public String getBianhao(){
return bianhao;
}
public void SetBianhao(String bianhao){
this.bianhao=bianhao;
}
public String getMingcheng(){
return mingcheng;
}
public void SetMingcheng(String mingcheng){
this.mingcheng=mingcheng;
}
public float getJiage(){
return jiage;
}
public void SetJiage(float jiage){
this.jiage=jiage;
}
}