java使用map建立学生表_学生类的操作,HashMap

[java]代码库import java.util.*;

public class Main{

public static void main(String[] args ) {

Scanner scan = new Scanner(System.in);

int num, no, score, i, j;

String name, op;

num = scan.nextInt();

Map map = new HashMap();

Student s;

for(i = 0; i < num; i++) {

no = scan.nextInt();

name = scan.next();

score = scan.nextInt();

s = new Student(no, name, score);

map.put(no, s);

}

num = scan.nextInt();

for(j = 0; j < num; j++) {

op = scan.next();

if(op.equals("add")){

no = scan.nextInt();

name = scan.next();

score = scan.nextInt();

s = new Student(no, name, score);

map.put(no, s);

}

else if(op.equals("delete")) {

no = scan.nextInt();

map.remove(no);

}

else if(op.equals("set")) {

no = scan.nextInt();

score = scan.nextInt();

map.get(no).setScore(score);

}

}

Iterator> iter = map.entrySet().iterator();

while(iter.hasNext()) {

Map.Entry entry = iter.next();

System.out.println(entry.getValue());

}

scan.close();

}

}

class Student{

int no;

String name;

int score;

public Student(int _no, String _name, int _score) {

no = _no;

name = _name;

score = _score;

}

public int getNo() {

return no;

}

public String getName() {

return name;

}

public int getScore() {

return score;

}

public void setScore(int sc) {

score = sc;

}

public String toString() {

return "no:" +no +" name:" +name +" score:" +score;

}

public boolean equals(Student s) {

if(this.no==s.getNo() && this.name.equals(s.getName()) && this.score==s.getScore())

return true;

else

return false;

}

public int hashcode() {

int result = 17;

result = 31*result + no;

return result;

}

}

694748ed64b9390909c0d88230893790.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中的HashMap是一种基于哈希实现的Map集合,它用于存储键值对,其中每个键都可以映射到一个唯一的值。HashMap的底层实现是一个数组和链结合的数据结构,它通过哈希函数将键映射到数组中的一个位置,然后在该位置上使用存储具有相同哈希值的键值对。 HashMap的常用方法有: 1. put(key, value):向HashMap中添加键值对。 2. get(key):根据键获取对应的值。 3. remove(key):根据键删除对应的键值对。 4. containsKey(key):判断HashMap中是否包含指定的键。 5. containsValue(value):判断HashMap中是否包含指定的值。 6. keySet():返回HashMap中所有键的集合。 7. values():返回HashMap中所有值的集合。 8. entrySet():返回HashMap中所有键值对的集合。 例如,我们可以建一个HashMap对象用于存储学生的姓名和对应的成绩: ``` HashMap<String, Integer> scores = new HashMap<>(); scores.put("Alice", 90); scores.put("Bob", 80); scores.put("Charlie", 70); ``` 然后,我们可以根据键来获取对应的值: ``` int score = scores.get("Alice"); // score = 90 ``` 也可以遍历HashMap中的所有键值对: ``` for (Map.Entry<String, Integer> entry : scores.entrySet()) { System.out.println(entry.getKey() + ": " + entry.getValue()); } ``` 需要注意的是,HashMap并不是线程安全的,如果在多线程环境下使用,需要进行额外的同步处理。另外,如果HashMap中的键对象是自定义的类,需要注意该类是否正确实现了equals()和hashCode()方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值