Java程序设计练习题7集合与泛型

判断题

R1-1

在JAVA的集合框架中,Map接口是自Collection接口继承而来。

T

F

单选题

R2-1

分数 2

对于java类,哪条语句是正确的util.ArrayList?

A.

该系列中的元素保证是独一无二的。

B

集合保证是不可变的。

C

集合中的元素是有序的。

D

集合中的元素保证是同步的

Which statement is true for the class java.util.ArrayList?

A.

The elements in the collection are guaranteed to be unique.

B.

The collection is guaranteed to be immutable.

C.

The elements in the collection are ordered.

D.

The elements in the collections are guaranteed to be synchronized


R2-2

分数 2

Which of the interfaces below is a collection as duplicating, ordered, unsorted?

A.

Collection

B.

ArrayList

C.

HashMap

D.

TreeSet


R2-3

分数 2

下面哪个Set是根据内容排序的?

A.

HashSet

B.

LinkedHashSet

C.

AbstractSet

D.

TreeSet


R2-4

分数 2

Java的集合框架中重要的接口java.util.Collection定义了许多方法。选项中哪个方法不是Collection接口所定义的?(     )

A.

compareTo(Object obj)

B.

boolean containsAll(Collection c)

C.

boolean remove(Object obj)

D.

int size()


R2-5

分数 2

Given code below:

    Set<Integer> s = new HashSet<Integer>();
    s.add(new Integer(1));
    s.add(new Integer(2));
    s.add(new Integer(1));

Which statement below is correct?

A.

It compiles but exception raises at line 4, for 1 is already in the set.

B.

It complies and there are three elements in s.

C.

It does not compile.

D.

It compiles, but only two elements left in s.


R2-6

分数 2

在Java中,关于HashMap类的描述,以下选项错误的是

A.

HashMap使用键/值得形式保存数据

B.

HashMap允许将null用作值

C.

HashMap允许将null用作键

D.

HashMap 能够保证其中元素的顺序


R2-7

分数 2

在Java中,( )类可用于创建链表数据结构的对象

A.

Collection

B.

HashMap

C.

LinkedList

D.

ArrayList


R2-8

分数 2

Given code below:

    List<String> ls = new ArrayList<String>();
    List<Object> lo = ls;
    lo.add(new Object());
    String s = ls.get(0);

Which statement below is correct?

A.

It compiles but exception raises at line 4

B.

It compiles but exception raises at line 2

C.

It compiles but exception raises at line 3

D.

It does not compile


R2-9

分数 2

Given code below:

    Set<Integer> s = new HashSet<Integer>();
    s.add(1);
    s.add(2);
    s.add(1);

以下哪项陈述是正确的@[A] (2)

A、 它可以编译,但s中只剩下两个元素。

B、 它不编译。

C、 它已编译,但在第4行出现异常,因为1已在集中。

D、 它符合标准,s中有三个元素。

Which statement below is correct?

A.

It compiles but exception raises at line 2, for 1 is not an objects of Integer

B.

It compiles but exception raises at line 4, for 1 is already in the set

C.

It compiles, but only two element left in s

D.

It does not compile because 1 and 2 are not objects of Integer


R2-10

分数 2

关于Java容器,下面哪条语句不正确?

A.

ArrayList按特定顺序保存元素。

B

TreeSet不能有任何重复的元素。

C

List、Set和Map,它们都有stream()接口。

D

LinkedList按特定顺序保存元素。

About Java containers, which statement below is NOT correct?

A.

ArrayList holds the elements in a particular sequence.

B.

TreeSet cannot have any duplicate elements.

C.

ListSet and Map, they all have stream() interface.

D.

LinkedList holds the elements in a particular sequence.


R2-11

分数 2

Java中,要对一个类实现for( : )形式的遍历,则该类必须实现下列哪一个接口?

A.

Comparable

B.

Cloneable

C.

Iterable

D.

Iterator


R2-12

分数 2

以下哪个接口是重复的、有序的、未排序的集合?

Which of the interfaces below is a collection as duplicating, ordered, unsorted?

A.

Map

B.

Set

C.

List

D.

Collection


R2-13

分数 2

list是一个ArrayList的对象,哪个选项的代码填写到//todo delete处,可以在Iterator遍历的过程中正确并安全的删除一个list中保存的对象?(     )

Iterator it = list.iterator();
        int index = 0;
        while (it.hasNext()){
              Object obj = it.next();
              if (needDelete(obj)) { //needDelete返回boolean,决定是否要删除
                   //todo delete
               }
              index ++;
        }

A.

list.remove(it.next());

B.

it.remove();

C.

list.remove(obj);

D.

list.remove(index);


R2-14

分数 2

Given code below:

Set<Integer> s = new HashSet<Integer>();
s.add(new Integer(1));
s.add(new Integer(2));
s.add(new Integer(1));

Which statement below is correct?

A.

It compiles but exception raises at line 4, for 1 is already in the set.

B.

It does not compile.

C.

It complies and there are three elements in s.

D.

It compiles, but only two elements left in s.


R2-15

分数 2

For code below:

ArrayList<Integer> a = new ArrayList<Integer>();
ArrayList<Double> b = new ArrayList<Double>();

Which statement below is NOT correct?

A.

a instanceof ArrayList is true

B.

a.getClass().equals(b.getClass()) is true

C.

a.getClass() == b.getClass() is false

D.

a.getClass() == b.getClass() is true


R2-16

分数 2

如果编译/运行以下代码行,会发生什么?

What will happen if you compile/run the following lines of code?

Vector a = new Vector();
a.addElement(10);
System.out.println(a.elementAt(0));

A.

Prints some garbage.

B.

Prints 10.

C.

Compilation error at line 3.

D.

Prints 11.


R2-17

分数 2

Given code below:

List<String> l1 = new ArrayList<>();
ArrayList<Integer> l2 = new ArrayList<>();
System.out.println(l1.getClass() == l2.getClass());

The result of compilation and running in Java 8 is:

A.

It compiles and exception raises at run-time

B.

It compiles and prints out true

C.

It does not compile

D.

It compiles and prints out false


R2-18

分数 1

使用Iterator时,判断是否存在下一个元素可以使用以下哪个方法?()

A.

hash()

B.

hasNext()

C.

next()

D.

hasPrevious()


R2-19

分数 2

Which most closely matches a description of a Java Map?

A.

A class for containing unique vector elements

B.

An interface that ensures that implementing classes cannot contain duplicate keys

C.

A vector of arrays for a 2D geographic representation

D.

A class for containing unique array elements


R2-20

分数 2

下面哪个Set是按照插入顺序排序的?

A.

AbstractSet

B.

HashSet

C.

LinkedHashSet

D.

TreeSet


R2-21

分数 2

关于Java容器,下面哪条语句不正确?
A.

映射有一组键值对象对
B

迭代器可以处理列表、集合和映射
C

集合不能有任何重复的元素
D

列表按特定顺序保存元素

About Java containers, which statement below is NOT correct?

A.

Map has group of key-value object pairs

B.

Iterator can deal with ListSet and Map

C.

Set cannot have any duplicate elements

D.

List holds the elements in a particular sequence


R2-22

分数 2

Given list an object of ArrayList, which code below for //todo delete can remove an element in the list correctly and safely?

        Iterator it = list.iterator();
        int index = 0;
        while (it.hasNext()){
              Object obj = it.next();
              if (needDelete(obj)) { // returns Boolean for removing or not
                   //todo delete
              }
              index ++;
        }

A.

it.remove();

B.

list.remove(it.next());

C.

list.remove(index);

D.

list.remove(obj);


R2-23

分数 2

下面哪个Map是排序的?

A.

LinkedHashMap

B.

Hashtable

C.

TreeMap

D.

WeakHashMap

E.

HashMap

填空题

R4-1

分数 2

作者 石俊萍

单位 吉首大学

使用Iterator遍历集合时,首先需要调用( )方法判断是否存在下一个元素,若存在下一个元素,则调用( )方法取出该元素。

@@[hasNext()](1)

@@[next()](1)


R4-2

分数 8

作者 翁恺

单位 浙江大学

给出以下代码:

public enum Main {
  PLUS   { int eval(int x, int y) { return x + y; } },
  MINUS  { int eval(int x, int y) { return x - y; } },
  TIMES  { int eval(int x, int y) { return x * y; } },
  DIVIDE { int eval(int x, int y) { return x / y; } };
  abstract int eval(int x, int y);
  public static void main(String args[]) {
          int x = 4;
        int y = 2;
        for (Main op : Main.values())
            System.out.printf("%d %s %d = %d%n", x, op, y, op.eval(x, y));
    }
}

程序运行结果为(一行一空):

4 PLUS 2 = 6

2 分

4 MINUS 2 = 2

2 分

4 TIMES 2 = 8

2 分

4 DIVIDE 2 = 2

2 分


R4-3

分数 2

作者 石俊萍

单位 吉首大学

Map集合中存储元素需要调用( )方法,要想根据该集合的键获取对应的值需要调用( )方法。

@@[put()](1)

1 分

@@[get()](1)

1 分


R4-4

分数 3

作者 翁恺

单位 浙江大学

The code below will print three lines.

class Pet {}
class Dog extends Pet {}
class Pug extends Dog {}
class Cat extends Pet {}
class Rodent extends Pet {}
class Gerbil extends Rodent {}
class Hamster extends Rodent {}

class Main {
    static HashMap<Integer, Class<? extends Pet>> map = new HashMap<Integer, Class<? extends Pet>>();
    static {
        map.put(Pet.class.getName().length(), Pet.class);
        map.put(Dog.class.getName().length(), Dog.class);
        map.put(Pug.class.getName().length(), Pug.class);
        map.put(Cat.class.getName().length(), Cat.class);
        map.put(Rodent.class.getName().length(), Rodent.class);
        map.put(Gerbil.class.getName().length(), Gerbil.class);
        map.put(Hamster.class.getName().length(), Hamster.class);
    }
    public static void main(String[] args) {
        for ( Integer i : map.keySet() )
            System.out.println(map.get(i).getName());
}}
  1. 1 分

        pta代码.Cat

  1. 1 分

        pta代码.Gerbil

  1. 1 分

        pta代码.Hamster


R4-5

分数 2

作者 石俊萍

单位 吉首大学

集合按照存储结构的不同可分为单列集合和双列集合,单列集合的根接口是( ),双列集合的根接口是( )。

Collection

1 分

Map

1 分


R4-6

分数 2

作者 翁恺

单位 浙江大学

请写出以下程序运行结果:

 //环境 JDK 1.5及以上
 public static void main(String args[])
    {
        Set<Integer> set=new TreeSet<Integer>();
        List<Integer> list=new ArrayList<Integer>();
        for (int i=-3;i<3;i++)
        {
            set.add(i);
            list.add(i);
        }
        for (int i=0;i<3;i++)
        {
            set.remove(i);
            list.remove(i);
        }
        System.out.println(set+" "+list);
    
    }

程序运行的输出结果为

[-3, -2, -1] [-2, 0, 2]

R7-9 统计Java程序中关键词的出现次数

分数 100

全屏浏览题目

切换布局

作者 段喜龙

单位 南昌航空大学

编写程序统计一个输入的Java源码中关键字(区分大小写)出现的次数。说明如下:

  • Java中共有53个关键字(自行百度)
  • 从键盘输入一段源码,统计这段源码中出现的关键字的数量
  • 注释中出现的关键字不用统计
  • 字符串中出现的关键字不用统计
  • 统计出的关键字及数量按照关键字升序进行排序输出
  • 未输入源码则认为输入非法

输入格式:

输入Java源码字符串,可以一行或多行,以exit行作为结束标志

输出格式:

  • 当未输入源码时,程序输出Wrong Format
  • 当没有统计数据时,输出为空
  • 当有统计数据时,关键字按照升序排列,每行输出一个关键字及数量,格式为数量\t关键字

输入样例:

在这里给出一组输入。例如:

//Test public method
public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }
exit

输出样例:

在这里给出相应的输出。例如:

1	float
3	if
2	int
2	new
2	public
3	this
2	throw

代码长度限制

16 KB

时间限制

400 ms

内存限制

package pta代码;

//import java.util.Arrays;
//import java.util.HashMap;
//import java.util.Map;
//import java.util.Scanner;
//import java.util.Set;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;

public class Main {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner cin = new Scanner(System.in);

		String a;
		StringBuilder ss = new StringBuilder();
		Map<String, Integer> map = new HashMap<String, Integer>();
		String[] key = { "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", "class", "const",
				"continue", "default", "do", "double", "else", "enum", "extends", "false", "final", "finally", "float",
				"for", "goto", "if", "implements", "import", "instanceof", "int", "interface", "long", "native", "new",
				"null", "package", "private", "protected", "public", "return", "short", "static", "strictfp", "super",
				"switch", "synchronized", "this", "throw", "throws", "transient", "true", "try", "void", "volatile",
				"while"

		};

		int j = 0;
		for (int i = 0;; i++) {
			a = cin.nextLine();
			if (a.equals("exit"))
				break;
			if (a.matches("(.*)//(.*)")) {
				String b[] = a.split("//");
				ss.append(b[0] + " ");
			} else {
				ss.append(a + " ");
			}
		}
		int count = 0;
		String s = ss.toString();
		Pattern p = Pattern.compile("\"(.*?)\"");
		Matcher m = p.matcher(s);
		while (m.find()) {
			s = s.replace(m.group(), " ");
			p = Pattern.compile("\"(.*?)\"");
			m = p.matcher(s);
		}
		p = Pattern.compile("/\\**(.*?)/");
		m = p.matcher(s);
		while (m.find()) {
			s = s.replace(m.group(), " ");
			m = p.matcher(s);
		}
		if (s.isEmpty()) {
			System.out.println("Wrong Format");
			System.exit(0);
		}
		s = s.replace("[", " ");
		s = s.replace("]", " ");
		s = s.replace("-", "a");
		s = s.replace("*", "a");
		s = s.replace("/", "a");
		s = s.replace("+", "a");
		s = s.replace(">", "a");
		s = s.replace("=", "a");
		s = s.replace("!", "a");
		s = s.replace(":", "a");
		s = s.replace("\\", "a");
		s = s.replaceAll("[^a-zA-Z]", " ");

		String[] s1 = s.split("[  ' ']");
		for (int i = 0; i < s1.length; i++) {
			for (j = 0; j < key.length; j++)
				if (s1[i].equals(key[j])) {
					map.put(key[j], 0);
				}
		}
		for (int i = 0; i < s1.length; i++) {
			for (j = 0; j < key.length; j++)
				if (s1[i].equals(key[j])) {
					count = map.get(key[j]);
					map.put(key[j], count + 1);
				}
		}
		Set set = map.keySet();
		Object[] arr = set.toArray();
		Arrays.sort(arr);
		for (Object k : arr) {
			System.out.println(map.get(k) + "\t" + k);
		}
	}
}

R7-10 list 存储动物对象

分数 10

全屏浏览题目

切换布局

作者 AMi

单位 临沂大学

本题要求在列表中存储动物,包括鸟和狗,请写代码完成下列内容:

1.定义抽象类Animal,包含私有属性name和age,为其完成setter、getter,带参构造方法,以及eclipse生成ToString方法

2.定义子类Bird继承Animal,完成带参构造方法,重写Tostring方法。

3.定义子类Dog继承Animal,添加属性leg,为其完成setter,getter,完成带参构造方法,重写ToString方法

4.在Main类的main方法中,定义列表list,在列表中规定只能放Dog和Bird,完成下列操作:

1.输入整数n,表示向列表中加入的对象的个数,然后向list中加入n个Animal
2.在加入每一个对象之前,若输入整数1,表示加入Dog对象,输入其他整数,加入Bird对象,然后通过键盘输入相关属性,创建对应对象,加入list中。
3.一次输出所有的list对象
4.键盘输入一个name,然后判断在列表中是否存在对象属性name与此相同,如果相同,输出其对象的类名,并输出对象的信息,
如果不存在对象name与键盘输入相同,显示“no this one"

输入格式:

请在这里写输入格式。例如:输入在一行中给出2个绝对值不超过1000的整数A和B。

输出格式:

请在这里描述输出格式。例如:对每一组输入,在一行中输出A+B的值。

输入样例:

在这里给出一组输入。例如:

4
1
tom 3 3
2
bir 2
1
may 3 5
2
baby 3
may
3
1
tom 3 2
2
may 4
1
jerry 3 1
tina

输出样例:

在这里给出相应的输出。例如:

[Dog[leg=3, name=tom, age=3], Bird[name=bir, age=2], Dog[leg=5, name=may, age=3], Bird[name=baby, age=3]]
Dog
Dog[leg=5, name=may, age=3]
[Dog[leg=2, name=tom, age=3], Bird[name=may, age=4], Dog[leg=1, name=jerry, age=3]]
no this one

代码长度限制

16 KB

时间限制

400 ms

内存限制

package pta代码;

import java.util.*;

class Animal {
	String name;
	String age;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAge() {
		return age;
	}

	public void setAge(String age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Animal [name=" + name + ", age=" + age + "]";
	}

	public String play() {
		return "Animal";
	}

}

class Bird extends Animal {
	public Bird(String s1, String s2) {
		name = s1;
		age = s2;
	}

	@Override
	public String toString() {
		return "Bird[name=" + name + ", age=" + age + "]";
	}

	@Override
	public String play() {
		return "Bird";
	}
}

class Dog extends Animal {
	String leg;

	public Dog(String s1, String s2, String s3) {
		name = s1;
		age = s2;
		leg = s3;
	}

	public String getLeg() {
		return leg;
	}

	public void setLeg(String leg) {
		this.leg = leg;
	}

	@Override
	public String toString() {
		return "Dog[leg=" + leg + ", name=" + name + ", age=" + age + "]";
	}

	@Override
	public String play() {
		return "Dog";
	}
}

public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		String s1, s2, s3;
		LinkedList<Animal> lk = new LinkedList<Animal>();
		for (int i = 0; i < n; i++) {
			int k = sc.nextInt();
			if (k == 1) {
				s1 = sc.next();
				s2 = sc.next();
				s3 = sc.next();
				Dog d = new Dog(s1, s2, s3);
				lk.add(d);
			} else {
				s1 = sc.next();
				s2 = sc.next();
				Bird d = new Bird(s1, s2);
				lk.add(d);
			}
		}

		System.out.printf("[");
		for (int i = 0; i < n; i++) {
			if (i == 0) {
				System.out.printf(lk.get(i).toString());
			} else {
				System.out.printf(", " + lk.get(i).toString());
			}

		}
		System.out.println("]");
		int i;
		s1 = sc.next();
		for (i = 0; i < n; i++) {
			// System.out.println(lk.get(i).getName().length());
			// System.out.println(s1.length());
			if (s1.equals(lk.get(i).getName())) {
				System.out.println(lk.get(i).play());
				System.out.printf(lk.get(i).toString());
				break;
			}
		}
		if (i == n) {
			System.out.print("no this one");
		}
	}

}

R7-11 sdut-Collection(Map)-1 读中国载人航天史,汇航天员数量,向航天员致敬

分数 10

全屏浏览题目

切换布局

作者 周雪芹

单位 山东理工大学

1986年,中国实施“863”计划,航天技术列入其中。以载人飞船开始起步,最终建成我国的空间站。 1992年9月21日,中国实施载人航天工程,并确定了三步走的发展战略:第一步,发射载人飞船,建成初步配套的试验性载人飞船工程。第二步,突破载人飞船和空间飞行器的交会对接技术,利用载人飞船技术改装、发射一个空间实验室。第三步,建造载人空间站。

在长期的奋斗中,我国航天工作者不仅创造了非凡的业绩,而且铸就了特别能吃苦、特别能战斗、特别能攻关、特别能奉献的载人航天精神。载人航天精神,是“两弹一星”精神在新时期的发扬光大,是我们伟大民族精神的生动体现,永远值得全党、全军和全国人民学习。

截至2021年4月,历任航天英雄名字如下:
杨利伟(神舟五号)
费俊龙、聂海胜(神舟六号)
翟志刚、景海鹏、刘伯明(神舟七号)
景海鹏、刘旺、刘洋(神舟九号)
聂海胜、张晓光、王亚平(神舟十号)
景海鹏、陈东(神舟十一号)

会编程的小伙伴们,请以他们姓名中的拼音字母排序,统计一下航天英雄们出征太空的次数,以实际行动向航天员们致敬!

输入格式:

每次航天飞船的编号为一行读入数据,分别读入每次飞上太空的航天英雄的姓名,名字中间有若干个空格分隔。
最后一行为“end“,表示输入结束。

输出格式:

以他们姓名中的拼音字母排序,统计航天英雄们出征太空的次数。
每位航天员占一行,航天员姓名与出征次数中间有一个空格。

输入样例:

YangLiWei杨利伟
FeiJunLong费俊龙    NieHaiSheng聂海胜
Zhaizhigang翟志刚   JingHaiPeng景海鹏           LiuBoMing刘伯明
JingHaiPeng景海鹏   LiuWang刘旺                 LiuYang刘洋
NieHaiSheng聂海胜   Zhangxiaoguang张晓光        WangYaPing王亚平
JingHaiPeng景海鹏   ChenDong陈东
end

输出样例:

ChenDong陈东 1
FeiJunLong费俊龙 1
JingHaiPeng景海鹏 3
LiuBoMing刘伯明 1
LiuWang刘旺 1
LiuYang刘洋 1
NieHaiSheng聂海胜 2
WangYaPing王亚平 1
YangLiWei杨利伟 1
Zhaizhigang翟志刚 1
Zhangxiaoguang张晓光 1

代码长度限制

15 KB

时间限制

400 ms

内存限制

package pta代码;

import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		@SuppressWarnings("resource")
		Scanner cin = new Scanner(System.in);
		String[] c = new String[20];
		int i = 0, j;
		int[] t = new int[20];
		while (true) {
			int f = 0;
			String s = cin.next();
			if (s.equals("end"))
				break;
			for (j = 0; j < i; j++) {
				if (c[j].equals(s)) {
					f = 1;
					break;
				}
			}
			if (f == 1) {
				t[j]++;
			} else {
				t[i] = 1;
				c[i] = s;
				i++;
			}
		}
		for (j = 0; j < i; j++) {
			System.out.println(c[j] + " " + t[j]);
		}
	}

}

R7-12 sdut-Colleciton-5 学生信息的添加与查询(HashMap)

分数 10

全屏浏览题目

切换布局

作者 周雪芹

单位 山东理工大学

设计一个学生信息添加和查询的系统,从键盘读入学生的数据,然后通过屏幕进行显示。

输入格式:

第一行有1个整数N,表示学生数量;

接下来有N行学生数据,分别表示学生的id(编号)、name(姓名)、birthday(生日)、score(成绩)属性的值,关键字(id)相同的记录代表同一个学生(如果id相同,后来读入的学生信息会覆盖已有的学生信息)

输出格式:

按照id从小到大的顺序,输出所有学生的属性名称及属性值,其中score(成绩)保留1位有效数字,具体输出格式见输出样例。

提示:可以利用Student类的toString()方法来实现类对象属性的展示。

输入样例:

5
0001  Mike    1990-05-20  98.5
0002  John    1992-05-20  67
0003  Hill    1994-05-20  36.5
0004  Christ  1996-05-20  86.5
0001  Jack    1998-05-20  96

输出样例:

Student [id=0001, name=Jack, birthday=1998年05月20日, score=96.0]
Student [id=0002, name=John, birthday=1992年05月20日, score=67.0]
Student [id=0003, name=Hill, birthday=1994年05月20日, score=36.5]
Student [id=0004, name=Christ, birthday=1996年05月20日, score=86.5]

代码长度限制

16 KB

时间限制

400 ms

内存限制

package pta代码;

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

class Student {
	String id;
	String name;
	String birth;
	double score;

	public Student(String id, String name, String birth, double score) {
		this.birth = birth;
		this.id = id;
		this.name = name;
		this.score = score;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", birthday=" + birth + ", score=" + score + "]";
	}
}

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		Map<String, Student> stu = new TreeMap<>();
		for (int i = 0; i < n; i++) {
			String id = sc.next();
			String name = sc.next();
			String birth = sc.next();
			String[] temp = birth.split("-");

			birth = temp[0] + "年" + temp[1] + "月" + temp[2] + "日";
			double score = sc.nextDouble();
			Student s = new Student(id, name, birth, score);
			if (stu.containsKey(id)) {
				stu.replace(id, s);
			} else
				stu.put(id, s);
		}

		for (Map.Entry<String, Student> entry : stu.entrySet()) {
			System.out.println(entry.getValue().toString());
		}

		sc.close();
	}
}

R7-13 删除序列的最大和最小值问题

分数 10

全屏浏览题目

切换布局

作者 abc618382

单位 河北科技大学

学者在进行数据统计的时候,为了避免极值的影响,通常会忽略掉最大值和最小值,然后对剩余元素进行统计,请编写程序完成去除极值的工作。

输入格式:

一行字符串,数字均为整数,之间使用空格分开(元素个数>=3)。

输出格式:

去除两端极值后的剩余元素,升序排列,之间使用空格分开

输入样例:

在这里给出一组输入。例如:

10 3 2 -1 5 3 4 3 0 3 2

输出样例:

在这里给出相应的输出。例如:

0 2 2 3 3 3 3 4 5

代码长度限制

16 KB

时间限制

400 ms

内存限制

package pta代码;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner cin = new Scanner(System.in);
		String str = cin.nextLine();

		// 分割字符串
		String[] s = str.split(" ");
		ArrayList<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < s.length; i++) {

			// 转成Integer存入ArrayList集合
			list.add(Integer.parseInt(s[i]));
		}

		// 调用Collections类的排序函数
		Collections.sort(list);

		// 删除最大最小值
		list.remove(0);
		list.remove(list.size() - 1);
		for (int i = 0; i < list.size(); i++) {
			if (i == 0) {
				System.out.print(list.get(i));
			} else {
				System.out.print(" " + list.get(i));
			}
		}
	}
}

  • 5
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
Java 集合框架是 Java 提供的一组接口和类,用于存储和操作对象的集合Java 集合框架提供了许多集合类,包括 List、Set、Map 等,这些集合类可以存储不同类型的对象,如整数、字符串、自定义对象等。 泛型Java 中的一个重要特性,它可以让我们编写更加可读性好、类型安全的代码。泛型允许我们在编译时指定集合中存储的元素类型,并检查代码是否符合类型安全原则。 下面是一个简单的 Java 集合泛型的示例代码: ```java import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CollectionDemo { public static void main(String[] args) { // 创建一个 List 集合,并添加元素 List<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("orange"); // 遍历 List 集合 for (String fruit : list) { System.out.println(fruit); } // 创建一个 Map 集合,并添加键值对 Map<String, Integer> map = new HashMap<>(); map.put("apple", 1); map.put("banana", 2); map.put("orange", 3); // 遍历 Map 集合 for (Map.Entry<String, Integer> entry : map.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } } ``` 在上面的代码中,我们创建了一个 List 集合和一个 Map 集合,并使用泛型指定集合中存储的元素类型。然后我们使用 add 方法向 List 集合中添加元素,使用 put 方法向 Map 集合中添加键值对。最后,我们使用 for 循环遍历集合,并输出集合中的元素和键值对。 使用 Java 集合泛型可以让我们更加方便地存储和操作数据,同时也可以让代码更加易读易维护。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

真题OK撒

你的打赏将是我最大的创作

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值