实验目的及要求:
(1)熟悉泛型的概念及用法;
(2)熟悉java的集合框架原理;
(3)掌握常用的集合及泛型类的用法:LinkedList、HashSet、HashMap
实验内容:
(1)定义一个泛型类Instrument,其中包括一个泛型方法void play(E x)。定义两种乐器类:Cello、Violin可以进行演奏。定义一个测试类进行测试。
public class Instrument<E> {
public void play (E a){
System.out.println(a.toString()+"在演奏!!");
}
}
public class Cello {
@Override
public String toString() {
return "Cello";
}
}
public class Violin {
@Override
public String toString() {
return "Violin";
}
}
public class Test {
public static void main(String[] args) {
Instrument<Cello> a1 = new Instrument();
Instrument<Violin> a2 = new Instrument();
a1.play(new Cello());
a2.play(new Violin());
}
}
(2)输入10个数字保存到List中,并按倒序显示出来。
可以用List、Set。
import java.util.*;
public class ListTest {
public static void main(String[] args) {
List<Double> l = new ArrayList<>();
Scanner in = new Scanner(System.in);
System.out.print("请输入10个数字:");
for (int i = 0; i < 10; i++){
l.add(in.nextDouble());
}
Collections.sort(l);
System.out.print("降序排列输出:");
for (int i = 9; i >= 0; i--){
System.out.print(l.get(i));
System.out.print(" ");
}
}
}
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class SetTest {
public static void main(String[] args) {
Set<Double> s = new TreeSet<>();
Scanner in = new Scanner(System.in);
System.out.print("请输入10个不同的数字:");
for (int i = 0; i < 10; i++) {
s.add(in.nextDouble());
}
s = ((TreeSet<Double>) s).descendingSet();
System.out.print("降序排列输出:");
s.forEach(x -> {
System.out.print(x);
System.out.print(" ");
});
}
}
(3)编写一个程序,把学生名和考试分数录入到Map中,并按分数显示前三名学生的名字。要求定义Student类,封装学生名和考试分数2个属性及方法。
Student:name、score
public class Student {
private String name;
private double score;
public Student(String name, double score) {
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
}
import java.util.*;
public class MapTest {
public static void main(String[] args) {
Map<String, Double> map = new HashMap<>();
Scanner in = new Scanner(System.in);
System.out.print("请问录入学生的人数为:");
int n = in.nextInt();
Student []st = new Student[n];
System.out.println("请在下面输入每个学生的姓名和成绩");
for (int i = 0; i < n; i++){
String name = in.next();
Double score = in.nextDouble();
st[i] = new Student(name, score);
map.put(name, score);
}
//转化排序
List<Map.Entry<String, Double>> list= new ArrayList<>();
list.addAll( map.entrySet());
Collections.sort(list, (o1, o2) -> {
if (o1.getValue() <= o2.getValue()) return 1;
else return -1;
});
int cnt = 1;
for(Map.Entry<String, Double> entry: list){
System.out.println("第"+String.valueOf(cnt)+"名:"+entry.getKey()+" "+String.valueOf(entry.getValue()));
cnt++;
if (cnt > 3) break;
}
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)