Java实验之泛型与集合框架

701 阅读5分钟

搭建流水线

实验要求 程序有时候需要将任务按流水式进行,例如评判体操选手的任务按流水式为依次的三个步骤:录入裁判给选手的分数,去掉一个最高分和最低分,计算出平均成绩,编写程序,搭建流水线,只需将评判体操选手的任务交给流水线即可。

本文分享给需要面试刷题的朋友,我特意整理了一下,里面的技术不是靠几句话就能讲清楚,多问题其实答案很简单,但是背后的思考和逻辑不简单,要做到知其然还要知其所以然。如果想学习Java工程化、高性能及分布式、深入浅出。性能调优、Spring,MyBatis,Netty源码,数据结构,jvm,多线程等等,由于篇幅有限,以下只展示小部分面试题,有需要完整版的朋友可以点一点链接跳转领取,链接:戳这里免费下载,获取码:掘金

运行效果

// DoThing.java
public abstract class DoThing {
    public abstract void doThing(double [] a);
    public abstract void setNext(DoThing next);
}
// DelMaxAndMin.java
import java.util.*;
public class DelMaxAndMin extends DoThing {
    DoThing nextDoThing;
    public void setNext(DoThing next){
        nextDoThing=next;
    }
    public void doThing(double []a){
        Arrays.sort(a);
        double []b=Arrays.copyOfRange(a,1,a.length);
        System.out.print("去掉一个最高分"+b[b.length-1]+",");
        System.out.print("去掉一个最低分"+b[0]);
        nextDoThing.doThing(b);
    }
}
// ComputerAver.java
public class ComputerAver extends DoThing {
    DoThing nextDoThing;
    public void setNext(DoThing next){
        nextDoThing=next;
    }
    public void doThing(double[]a){
        double sum=0;
        for(int i=0;i<a.length;i++){
            sum=sum+a[i];
        }
        double aver=sum/a.length;
        System.out.print("选手最后得分"+aver);
    }
}
// Main.java
public class Main {

    public static void main(String[] args) {
        StreamLine line=new StreamLine();
        double []a=new double[1];
        line.giveResult(a);
    }
}

排序与查找

实验要求

编写一个Book类,该类至少有price成员变量。该类要实现Comparable接口,在接口的compareTo()方法中规定Book类两个实例的大小关系为二者的price成员的大小关系。 编写一个主类SortSearchMainClass,在main()方法中将Book类的若干个对象存放到一个链表中,然后再用Book类创建一个新的对象,并检查这个对象和链表中哪些对象相等。

运行结果

代码

// Book.java
public class Book implements Comparable{
    double price;
    String name;
    public void setPrice(double c){
        price=c;
    }
    public double getPrice(){
        return price;
    }
    public void setName(String n){
        name=n;
    }
    public String getName(){
        return name;
    }
    public int compareTo(Object object){
        Book bk=(Book) object;
        int difference=(int) ((this.getPrice()- bk.getPrice())*10000);
        return difference;
    }
}
// Main.java
import java.util.*;
public class Main {

    public static void main(String[] args) {
        List<Book>bookList=new LinkedList<Book>();
        String bookName[]={"Java 基础教程","XML基础教程","JSP基础教程","C++基础教程",
        "J2ME编程","操作系统","数据库技术"};
        double bookPrice[]={29,21,22,29,34,32,29};
        Book book[]=new Book[bookName.length];
        for(int k=0;k<book.length;k++){
            book[k]=new Book();
            book[k].setName(bookName[k]);
            book[k].setPrice(bookPrice[k]);
            bookList.add(book[k]);
        }
        Book newBook=new Book();
        newBook.setPrice(29);
        newBook.setName("Java与模式");
        Collections.sort(bookList);
        int m=-1;
        System.out.println("新书:"+newBook.getName()+"("+newBook.getPrice()+")与下列图书:");
        while ((m=Collections.binarySearch(bookList,newBook,null))>=0){
            Book bk=bookList.get(m);
            System.out.println("\t"+bk.getName()+"("+bk.getPrice()+")");
            bookList.remove(m);
        }
        System.out.println("价钱相同。");
    }
}

使用TreeSet排序

实验要求

编写一个应用程序,用户分别从两个文本框输入学生的姓名和分数,程序按成绩排序将这些学生的姓名和分数显示在一个文本区内。

运行效果

// Student.java
public class Student implements Comparable{
    String name;
    int score;
    Student(String name,int score){
        this.name=name;
        this.score=score;
    }
    public int compareTo(Object b){
        Student st=(Student) b;
        int m=this.score-st.score;
        if(m!=0){
            return m;
        }
        else {
            return 1;
        }
    }
    public int getScore(){
        return score;
    }
    public String getName(){
        return name;
    }
}
// StudentFrame.java
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.Style;

public class StudentFrame extends JFrame implements ActionListener{
    JTextArea showArea;
    JTextField inputName,inputScore;
    JButton button;
    TreeSet<Student> treeSet;
    StudentFrame(){
        treeSet=new TreeSet<Student>();
        showArea=new JTextArea();
        showArea.setFont(new Font("",Font.BOLD,20));
        inputName=new JTextField(5);
        inputScore=new JTextField(5);
        button=new JButton("确定");
        button.addActionListener((ActionListener) this);
        JPanel pNorth=new JPanel();
        pNorth.add(new JLabel("Name:"));
        pNorth.add(inputName);
        pNorth.add(new JLabel("Score:"));
        pNorth.add(inputScore);
        pNorth.add(button);
        add(pNorth,BorderLayout.NORTH);
        add(showArea,BorderLayout.CENTER);
        setSize(300,320);
        setVisible(true);
        validate();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent e){
        String name=inputName.getText();
        int score=0;
        try{
            score=Integer.parseInt(inputScore.getText().trim());
            if(name.length()>0){
                Student stu=new Student(name,score);
                treeSet.add(stu);
                show(treeSet);
            }
        }
        catch (NumberFormatException exp){
            inputScore.setText("请输入数字字符");
        }
    }
    public void show(TreeSet tree){
        showArea.setText(null);
        Iterator<Student> te=treeSet.iterator();
        while (te.hasNext()){
            Student stu=te.next();
            showArea.append("Name:"+stu.getName()+"Score:"+stu.getScore()+"\n");
        }
    }
    public static void main(String[] args) {
        new StudentFrame();
    }
}

扫雷小游戏

实验要求

编写一个Block类,Block对象具有String类型和boolean类型的成员变量,Block对象可以使用setName(String)方法、getName()方法、isName()方法、setIsMine()方法来设置对象的名字、返回该对象的名字、返回对象的boolean类型成员的值、设置对象的boolean类型成员的值。 编写一个LayMines类,该类提供一个public void layMinesForBlock(Block block[][],int mineCount)方法,该方法可以随机地将参数block指定的二维数组中的mineCount个单元设置为“雷”。 编写一个BlockView类,该类的实例为Block对象提供视图。 编写MineFrame窗体类,该类将Block类的实例和BlockView类的实例作为成员,并负责二者之间的交互。

运行结果

代码

// Block.java
public class Block {
    String name;
    int number;
    boolean boo=false;
    public void setName(String name){
        this.name=name;
    }
    public void setNumber(int n){
        number=n;
    }
    public int getNumber(){
        return number;
    }
    public String getName(){
        return name;
    }
    boolean isMine(){
        return boo;
    }
    public void setIsMine(boolean boo){
        this.boo=boo;
    }
}

// LayMine.java
import java.util.*;
public class LayMine {
    public void layMinesForBlock(Block block[][],int mineCount){
        int row= block.length;;
        int column=block[0].length;
        LinkedList<Block>list=new LinkedList<Block>();
        for(int i=0;i<row;i++){
            for(int j=0;j<column;j++){
                list.add(block[i][j]);
            }
        }
        while (mineCount>0){
            int size=list.size();
            int randomIndex=(int) (Math.random()*size);
            Block b=list.get(randomIndex);
            b.setName("雷");
            b.setIsMine(true);
            list.remove(randomIndex);
            mineCount--;
        }
        for(int i=0;i<row;i++){
            for(int j=0;j<column;j++) {
                if (block[i][j].isMine()) {
                }
                else {
                    int mineNumber = 0;
                    for (int k = Math.max(i - 1, 0); k <= Math.min(i + 1, row - 1); k++) {
                        for (int t = Math.max(j - 1, 0); t <= Math.min(j + 1, column - 1); t++) {
                            if (block[k][t].isMine())
                                mineNumber++;
                        }
                    }
                    if (mineNumber > 0) {
                        block[i][j].setName("" + mineNumber);
                        block[i][j].setNumber(mineNumber);
                    } else {
                        block[i][j].setName(" ");
                        block[i][j].setNumber(mineNumber);
                    }

                }
            }
        }
    }
}
// BlockView.java
import java.awt.*;
import javax.swing.*;
public class BlockView extends JPanel{
    JLabel blockName;
    JButton blockCover;
    CardLayout card;
    BlockView(){
        card=new CardLayout();
        setLayout(card);
        blockName=new JLabel();
        blockCover=new JButton();
        add("Cover",blockCover);
        add("name",blockName);
    }
    public void setName(String name){
        blockName.setText(name);
    }
    public String getName(){
        return blockName.getText();
    }
    public void seeBlockName(){
        card.show(this,"name");
        validate();
    }
    public void seeBlockCover(){
        card.show(this,"Cover");
        validate();
    }
    public JButton getBlockCover(){
        return blockCover;
    }
}
// MineMainFrame.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MineMainFrame extends JFrame implements ActionListener{
    JButton reStart;
    Block block[][];
    BlockView blockView[][];
    LayMine lay;
    int row=10,colum=12,mineeCount=22;
    int colorSwitch=0;
    JPanel pCenter,pNorth;
    public MineMainFrame(){
        reStart=new JButton("重新开始");
        pCenter=new JPanel();
        pNorth=new JPanel();
        pNorth.setBackground(Color.CYAN);
        block=new Block[row][colum];
        for(int i=0;i<row;i++){
            for(int j=0;j<colum;j++)
                block[i][j]=new Block();
        }
        lay=new LayMine();
        lay.layMinesForBlock(block,mineeCount);
        blockView=new BlockView[row][colum];
        pCenter.setLayout(new GridLayout(row,colum));
        for (int i=0;i<row;i++){
            for(int j=0;j<colum;j++){
                blockView[i][j]=new BlockView();
                blockView[i][j].setName(block[i][j].getName());
                pCenter.add(blockView[i][j]);
                blockView[i][j].getBlockCover().addActionListener(this);
            }
        }
        reStart.addActionListener(this);
        pNorth.add(reStart);
        add(pNorth,BorderLayout.NORTH);
        add(pCenter,BorderLayout.CENTER);
        setSize(200,232);
        setVisible(true);
        validate();
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    public void actionPerformed(ActionEvent e){
        JButton source=(JButton)e.getSource();
        if(source!=reStart){
            int m=-1,n=-1;
            for(int i=0;i<row;i++){
                for(int j=0;j<colum;j++){
                    if(source==blockView[i][j].getBlockCover()){
                        m=i;
                        n=j;
                        break;
                    }
                }
            }
            if(block[m][n].isMine()){
                for(int i=0;i<row;i++){
                    for (int j=0;j<colum;j++){
                        blockView[i][j].getBlockCover().removeActionListener(this);
                        if(block[i][j].isMine())
                            blockView[i][j].seeBlockName();
                    }
                }
            }
            else{
                if(block[m][n].getNumber()>0)
                    blockView[m][n].seeBlockName();
                else if(block[m][n].getNumber()==0)
                    for(int k =Math.max(m-1,0);k<=Math.min(m+1,row-1);k++){
                        for(int t = Math.max(n-1,0); t<=Math.min(n+1,colum-1); t++) {
                            blockView[k][t].seeBlockName();
                        }
                }
            }
        }
        if(source==reStart){
            for(int i=0;i<row;i++){
                for(int j=0;j<colum;j++)
                    block[i][j].setIsMine(false);
            }
            lay.layMinesForBlock(block,mineeCount);
            for(int i=0;i<row;i++){
                for(int j=0;j<colum;j++){
                    blockView[i][j].setName(block[i][j].getName());
                    blockView[i][j].seeBlockCover();
                    blockView[i][j].getBlockCover().addActionListener(this);
                }
            }
        }
    }
    public static void main(String args[]){
        new MineMainFrame();
    }
}

本文分享给需要面试刷题的朋友,我特意整理了一下,里面的技术不是靠几句话就能讲清楚,多问题其实答案很简单,但是背后的思考和逻辑不简单,要做到知其然还要知其所以然。如果想学习Java工程化、高性能及分布式、深入浅出。性能调优、Spring,MyBatis,Netty源码,数据结构,jvm,多线程等等,由于篇幅有限,以下只展示小部分面试题,有需要完整版的朋友可以点一点链接跳转领取,链接:戳这里免费下载,获取码:掘金