20165206 The tenth week after class

20165206 The tenth week after class

1. Relevant knowledge points

  • Generic class declaration: When a generic class is declared and an object is created, a pair of "<>" is added after the class name, and the generic type in "<>" must be replaced with a specific type.

  • Linked list: A data structure composed of several objects called nodes, used to dynamically decrease or increase data items.

  • LinkedList in java.util package

  • Traversal: Traverse the linked list, using iterators. A linked list object can use the iterator() method to obtain an Iterator object, which is an iterator for the current linked list.

  • Sort:
    public static sort(List

  • Find:
    int binarySearch(List

  • Shuffle and rotate:
    public static void shuffle(List

  • A stack is a "last-in, first-out" data structure that can only perform input or output data operations at one end. The operation of inputting data to the stack is called "push", and the operation of outputting data from the stack is called "pop".

  • Tree Set: TreeSet

    2. Supplementary content in class

- Data Structure - Sorting

Code:

import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedList;
public class StudentTest {
    public  static void main(String[] args) {
        LinkedList<Student> mylist = new LinkedList<>();
        mylist.add(new Student(20165204,"贾普涵",20,88,92,89));
        mylist.add(new Student(20165205,"刘喆君",20,89,91,75));
        mylist.add(new Student(20165206,"韩啸",20,90,90,90));
        mylist.add(new Student(20165207,"李天林",20,91,89,78));
        mylist.add(new Student(20165208,"孔月",20,92,88,83));
        System.out.println("排序前:");
        for (Student student : mylist)
        {
            System.out.println(student);
        }
        SortByTotal_score sortBytotal_score = new SortByTotal_score();
        Collections.sort(mylist, sortBytotal_score);
        SortByID sortByID = new SortByID();
        Collections.sort(mylist, sortByID);
        System.out.println("按学号进行排序后:");
        for (Student student : mylist) {
            System.out.println(student);
        }

        Collections.sort(mylist, sortBytotal_score);
        System.out.println("按总成绩进行排序后:");
        for (Student student : mylist) {
            System.out.println(student);
        }
    }
}

class Student {

    private int id;//表示学号
    private String name;//表示姓名
    private int age;//表示年龄
    private double computer_score;//表示计算机课程的成绩
    private double english_score;//表示英语课的成绩
    private double maths_score;//表示数学课的成绩
    private double total_score;// 表示总成绩
    private double ave_score; //表示平均成绩

    @Override
    public String toString() {
        return "Student[name:"+name+",age:"+age+",number:"+id+",total_score"+total_score+"]";
    }

    public Student(int id, String name, int age, double computer_score,
                   double english_score, double maths_score) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.computer_score = computer_score;
        this.english_score = english_score;
        this.maths_score = maths_score;
    }

    public int getId() {
        return id;
    }//获得当前对象的学号,

    public double getComputer_score() {
        return computer_score;
    }//获得当前对象的计算机课程成绩,

    public double getMaths_score() {
        return maths_score;
    }//获得当前对象的数学课程成绩,

    public double getEnglish_score() {
        return english_score;
    }//获得当前对象的英语课程成绩,

    public void setId(int id) {
        this.id = id;
    }// 设置当前对象的id值,

    public void setComputer_score(double computer_score) {
        this.computer_score = computer_score;
    }//设置当前对象的Computer_score值,

    public void setEnglish_score(double english_score) {
        this.english_score = english_score;
    }//设置当前对象的English_score值,

    public void setMaths_score(double maths_score) {
        this.maths_score = maths_score;
    }//设置当前对象的Maths_score值,

    public double getTotalScore() {
        total_score=computer_score + maths_score + english_score;
        return total_score;
    }// 计算Computer_score, Maths_score 和English_score 三门课的总成绩。

    public double getAveScore() {
        return getTotalScore() / 3;
    }// 计算Computer_score, Maths_score 和English_score 三门课的平均成绩。

}

class SortByID implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return o1.getId() - o2.getId();
    }

}
class SortByTotal_score implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        return (int)( o1.getTotalScore() - o2.getTotalScore());
    }
}

Run the screenshot:

- Data structure - singly linked list

Code:

import java.util.*;
public class MyList {
    public static void main(String [] args) {
        //选用合适的构造方法,用你学号前后各两名同学的学号创建四个结点
        LinkedList<String> mylist=new LinkedList<String>();
        mylist.add("20165204");
        mylist.add("20165205");
        mylist.add("20165207");
        mylist.add("20165208");
        //把上面四个节点连成一个没有头结点的单链表
        System.out.println("遍历单链表,打印初始链表");
        Iterator<String> iterator=mylist.iterator();
        while(iterator.hasNext()){
            String te=iterator.next();
            System.out.println(te);
        }
        //遍历单链表,打印每个结点的
        mylist.add("20165206");
        Collections.sort(mylist);
        //把你自己插入到合适的位置(学号升序)
        System.out.println("遍历单链表,打印插入我的学号排序后的链表");
        iterator=mylist.iterator();
        while(iterator.hasNext()){
            String te=iterator.next();
            System.out.println(te);
        }
        //遍历单链表,打印每个结点的
        mylist.remove("20165206");
        //从链表中删除自己
        System.out.println("遍历单链表,打印删除我的学号后的链表");
        iterator=mylist.iterator();
        while(iterator.hasNext()){
            String te=iterator.next();
            System.out.println(te);
        }
        //遍历单链表,打印每个结点的
    }
}

class Node<T>                             //单链表结点类,T指定结点的元素类型
{
    public T data;                               //数据域,存储数据元素
    public Node<T> next;                         //地址域,引用后继结点

    public Node(T data, Node<T> next)            //构造结点,data指定数据元素,next指定后继结点
    {
        this.data = data;                        //T对象引用赋值
        this.next = next;                        //Node<T>对象引用赋值
    }
    public Node()
    {
        this(null, null);
    }
    public String toString()                     //返回结点数据域的描述字符串
    {
        return this.data.toString();
    }
}

Run the screenshot:

3. Code Analysis

  • Example15_1
class Cone<E> { 
   double height;
   E bottom;           //用泛型类E声明对象bottom
   public Cone (E b) {
      bottom=b;   //给泛型类对象赋值
   }
   public void setHeight(double h) {
      height=h;
   }
   public double computerVolume() {
      String s=bottom.toString();//泛型变量只能调用从Object类继承的或重写的方法
      double area=Double.parseDouble(s); 
      return 1.0/3.0*area*height; 
   }
}

class Rect {
   double sideA,sideB,area; 
   Rect(double a,double b) {
     sideA=a;
     sideB=b;
   } 
   public String toString() {
      area=sideA*sideB;
      return ""+area;
   }
}

class Circle {
   double area,radius; 
   Circle(double r) {
      radius=r;
   } 
   public String toString() { //重写Object类的toString()方法
      area=radius*radius*Math.PI;
      return ""+area;
   }
}

public class Example15_1 {
   public static void main(String args[]) {
      Circle circle=new Circle(10);
      Cone<Circle> coneOne=new Cone<Circle>(circle);//创建一个(圆)锥对象  
      coneOne.setHeight(16);
      System.out.println(coneOne.computerVolume());
      Rect rect=new Rect(15,23);
      Cone<Rect> coneTwo=new Cone<Rect>(rect);//创建一个(方)锥对象
      coneTwo.setHeight(98); 
      System.out.println(coneTwo.computerVolume());
  }
}

This example is a specific example of using a generic class to declare an object. It should be noted that when a generic class declares and creates an object, there is a pair of "<>" after the class name, and the "<>" must be replaced with a specific type "Generics in .
In this example, the Cone class is a generic class. When a Cone object calculates the volume, it only cares whether its base can calculate the area, and does not care about the type of the base.

  • Example15_2
import java.util.*;
public class Example15_2 {
   public static void main(String args[]){
      List<String> list=new LinkedList<String>();
      //定义一个空链表
      for(int i=0;i<=60096;i++){
             list.add("speed"+i);
      }
      Iterator<String> iter=list.iterator();  //获取链表中的迭代器
      long starttime=System.currentTimeMillis();
      while(iter.hasNext()){
           String te=iter.next();
      }
      //进行遍历
      long endTime=System.currentTimeMillis();
      long result=endTime-starttime;
      System.out.println("使用迭代器遍历集合所用时间:"+result+"毫秒");
      starttime=System.currentTimeMillis();
      for(int i=0;i<list.size();i++){
          String te=list.get(i);
      }
      endTime=System.currentTimeMillis();
      result=endTime-starttime;
      System.out.println("使用get方法遍历集合所用时间:"+result+"毫秒");
    }
}

This example mainly introduces the use of iterators in linked lists, and compares the time it takes to traverse the linked list using iterators and using get(int index) to traverse the linked list.

  • Example15_3
import java.util.*;
public class Example15_3 {
    public static void main(String args[]){
        LinkedList mylist=new LinkedList();//定义一个空链表
        mylist.add("你");                 //链表中的第一个节点
        mylist.add("好");                 //链表中的第二个节点
        int number=mylist.size();         //获取链表的长度
        for(int i=0;i<number;i++){
          String temp=(String)mylist.get(i); //必须强制转换取出的数据
          System.out.println("第"+i+"节点中的数据:"+temp);
        } 
        Iterator iter=mylist.iterator();
        while(iter.hasNext()) {
          String te=(String)iter.next();  //必须强制转换取出的数据
          System.out.println(te);
        }
   }
}

This example mainly introduces the use of the add(Object obj) method to add nodes to the linked list in turn, and the need for type conversion when using generic classes.

  • Example15_4
import java.util.*;
class Student implements Comparable { 
   int height=0;
   String name;
   Student(String n,int h) {
      name=n;
      height = h;
     
   }
   public int compareTo(Object b) { // 两个Student对象相等当且仅当二者的height值相等
     Student st=(Student)b;
     return (this.height-st.height);
   }
}
public class Example15_4 {
    public static void main(String args[ ]) { 
       List<Student> list = new LinkedList<Student>();
       //定义一个空链表
       list.add(new Student("张三",188));
       list.add(new Student("李四",178));
       list.add(new Student("周五",198)); 
       //向链表中依次添加元素
       Iterator<Student> iter=list.iterator();
       System.out.println("排序前,链表中的数据");
       while(iter.hasNext()){
          Student stu=iter.next();
          System.out.println(stu.name+ "身高:"+stu.height);
       }
       //对链表进行遍历
       Collections.sort(list);
       //进行升序排序
       System.out.println("排序后,链表中的数据");
       iter=list.iterator();
       while(iter.hasNext()){
          Student stu=iter.next();
          System.out.println(stu.name+ "身高:"+stu.height);
       }
       Student zhaoLin = new Student("zhao xiao lin",178);
       int index = Collections.binarySearch(list,zhaoLin,null);
       if(index>=0) {
            System.out.println(zhaoLin.name+"和链表中"+list.get(index).name+"身高相同");
       }
    }
}

This example mainly introduces how to compare objects of a class through Comparable and sort them in ascending order through Collections.sort.

  • Example15_5
import java.util.*;
public class Example15_5 {
    public static void main(String args[ ]) { 
       List<Integer> list = new LinkedList<Integer>();
       //定义一个空链表
       for(int i=10;i<=50;i=i+10)
           list.add(new Integer(i));
       System.out.println("洗牌前,链表中的数据");
       Iterator<Integer> iter=list.iterator();
       while(iter.hasNext()){
          Integer n=iter.next();
          System.out.printf("%d\t",n.intValue());
       }
       //遍历链表
       Collections.shuffle(list);
       //按洗牌算法重新随机排列
       System.out.printf("\n洗牌后,链表中的数据\n");
       iter=list.iterator();
       while(iter.hasNext()){
          Integer n=iter.next();
          System.out.printf("%d\t",n.intValue());
       }
       System.out.printf("\n再向右旋转1次后,链表中的数据\n");
       Collections.rotate(list,1);
       //旋转链表中的数据
       iter=list.iterator();
       while(iter.hasNext()){
          Integer n=iter.next();
          System.out.printf("%d\t",n.intValue());
       }
      
    }
}

This example mainly introduces how to rearrange the data through the shuffle() method and rotate the data in the linked list through the rotate() method.

  • Example15_6
import java.util.*;
public class Example15_6 {
   public static void main(String args[]) {
      Stack<Integer> stack=new Stack<Integer>();
      //定义一个堆栈对象
      stack.push(new Integer(1)); 
      stack.push(new Integer(1));
      //进行压栈
      int k=1;
      while(k<=10) {
        for(int i=1;i<=2;i++) {
          Integer F1=stack.pop();
          int f1=F1.intValue();
          Integer F2=stack.pop();
          int f2=F2.intValue();
          Integer temp=new Integer(f1+f2);
          System.out.println(""+temp.toString()); 
          stack.push(temp);
          stack.push(F2);
          k++;
        }
      } 
   }
}

This example uses the stack to output items of a recursive sequence.

  • Example15_7
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;   
import java.io.*;
import java.util.*;
class WindowWord extends JFrame {
   JTextField inputText,showText;
   WordPolice police;           //监视器
   WindowWord() {
      setLayout(new FlowLayout());
      inputText=new JTextField(6);
      showText=new JTextField(6);
      add(inputText); 
      add(showText);
      police=new WordPolice();
      police.setJTextField(showText);
      inputText.addActionListener(police);
      setBounds(100,100,400,280);
      setVisible(true);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
}

class WordPolice implements ActionListener {
   JTextField showText;
   HashMap<String,String> hashtable;
   //定义一个散列映射对象
   File file=new File("word.txt");
   Scanner sc=null;
   WordPolice() {
     hashtable=new HashMap<String,String>();
     try{ sc=new Scanner(file);
          while(sc.hasNext()){
             String englishWord=sc.next();
             String chineseWord=sc.next(); 
             hashtable.put(englishWord,chineseWord); 
          }
     }
     catch(Exception e){}  
   }
   public void setJTextField(JTextField showText) {
      this.showText=showText;
   }
   public void actionPerformed(ActionEvent e) {
      String englishWord=e.getActionCommand();
      if(hashtable.containsKey(englishWord)) {
         String chineseWord=hashtable.get(englishWord);
         showText.setText(chineseWord);
      }
      else {
         showText.setText("没有此单词");
      }  
   }
}

public class Example15_7 {
   public static void main(String args[]) {
      WindowWord win=new WindowWord();
      win.setTitle("英-汉小字典");
   }
}

This example is a query based on a hash map. It is a GUI program for querying English words. The user enters an English word and confirms it, and the Chinese translation is displayed on the other side.

  • Example15_8
import java.util.*;
class Student implements Comparable {
   int english=0;
   String name;
   Student(int english,String name) {
      this.name=name;
      this.english=english;
   }
   public int compareTo(Object b) {
      Student st=(Student)b;
      return (this.english-st.english);
   }
}
public class Example15_8 {
  public static void main(String args[]) {
     TreeSet<Student> mytree=new TreeSet<Student>();
     //定义一个树集对象
     Student st1,st2,st3,st4;
     st1=new Student(90,"赵一");
     st2=new Student(66,"钱二");
     st3=new Student(86,"孙三");
     st4=new Student(76,"李四");
     mytree.add(st1);
     mytree.add(st2);
     mytree.add(st3);
     mytree.add(st4);
     //依次添加数据
     Iterator<Student> te=mytree.iterator();
     while(te.hasNext()) {
        Student stu=te.next();
        System.out.println(""+stu.name+" "+stu.english);
        //遍历并打印数据
     }
  }
}

This example is to store four objects from low to high through a tree set according to English scores.

  • Example15_9
import java.util.*;
class StudentKey implements Comparable { 
   double d=0; 
   StudentKey (double d) {
     this.d=d;
   }
   public int compareTo(Object b) {
     StudentKey st=(StudentKey)b;
     if((this.d-st.d)==0)
        return -1;
     else
        return (int)((this.d-st.d)*1000);
  }
}
class Student { 
    String name=null;
    double math,english;
    Student(String s,double m,double e) {
       name=s; 
       math=m;
       english=e;
    }
}
public class Example15_9 {
   public static void main(String args[ ]) {
      TreeMap<StudentKey,Student>  treemap= new TreeMap<StudentKey,Student>();
      //定义一个树映射对象
      String str[]={"赵一","钱二","孙三","李四"};
      double math[]={89,45,78,76};
      double english[]={67,66,90,56};
      Student student[]=new Student[4];
      for(int k=0;k<student.length;k++) {
         student[k]=new Student(str[k],math[k],english[k]);
      }
      StudentKey key[]=new StudentKey[4] ;
      for(int k=0;k<key.length;k++) {
         key[k]=new StudentKey(student[k].math); //关键字按数学成绩排列大小
      }
      for(int k=0;k<student.length;k++) {
         treemap.put(key[k],student[k]);          
      }
      int number=treemap.size();
      System.out.println("树映射中有"+number+"个对象,按数学成绩排序:");
      Collection<Student> collection=treemap.values();
      Iterator<Student> iter=collection.iterator();
      while(iter.hasNext()) {
         Student stu=iter.next();
         System.out.println("姓名 "+stu.name+" 数学 "+stu.math);
      }
      treemap.clear();
      for(int k=0;k<key.length;k++) {
         key[k]=new StudentKey(student[k].english);//关键字按英语成绩排列大小
      }
      for(int k=0;k<student.length;k++) {
         treemap.put(key[k],student[k]);
      }
      number=treemap.size();
      System.out.println("树映射中有"+number+"个对象:按英语成绩排序:");
      collection=treemap.values();
      iter=collection.iterator();
      while(iter.hasNext()) {
         Student stu=(Student)iter.next();
         System.out.println("姓名 "+stu.name+" 英语 "+stu.english);
      }
    }
}

The example uses TreeMap to sort by students' English and math scores, respectively.

  • Example15_10
import java.util.*;
public class Example15_10 {
   public static void main(String args[]) {
      ArrayList<Integer> list=new ArrayList<Integer>();
      for(int i=0;i<10;i++) {
         list.add(i);  //自动装箱,实际添加到list中的是new Integer(i)。
      }
      for(int k=list.size()-1;k>=0;k--) {
         int m=list.get(k);  //自动拆箱,获取Integer对象中的int型数据
         System.out.printf("%3d",m);
      }
   }
}

This example performs automatic boxing and unboxing, that is, when a basic data type is added to a data structure like a linked list, the conversion of the basic data type to the corresponding object is automatically completed, and the corresponding object to the basic data type is automatically completed when the object is obtained. convert.

Fourth, after-school programming topics

  • Use the stack structure to output several items of an, where an=2an-1 +2an-2, a1=3, a2=8.
import java.util.*;
public class E {
    public static void main(String args[]) {
        Stack<Integer> stack=new Stack<Integer>();
        stack.push(new Integer(3));
        stack.push(new Integer(8));
        int k=1;
        while(k<=10) {
            for(int i=1;i<=2;i++) {
                Integer F1=stack.pop();
                int f1=F1.intValue();
                Integer F2=stack.pop();
                int f2=F2.intValue();
                Integer temp=new Integer(2*f1+2*f2);
                System.out.println(""+temp.toString());
                stack.push(temp);
                stack.push(F2);
                k++;
            }
        }
    }
}

Run the screenshot:

  • Write a program to store the students' English transcripts in the linked list into a tree set, so that they are automatically sorted by grades, and the sorted results are output.
import java.util.*; 
class Student implements Comparable {
    int english=0; 
String name; 
   Student(int english,String name) {
       this.name=name;
       this.english=english;
    } 
   public int compareTo(Object b) {
       Student st=(Student)b;
       return (this.english-st.english);
    }
 } 
public class E { 
  public static void main(String args[]) { 
     List<Student> list=new LinkedList<Student>();
      int score []={65,76,45,99,77,88,100,79}; 
     String name[]={"张三","李四","旺季","加戈","为哈","周和","赵李","将集"};
       for(int i=0;i<score.length;i++){ 
             list.add(new Student(score[i],name[i]));
      } 
     Iterator<Student> iter=list.iterator(); 
     TreeSet<Student> mytree=new TreeSet<Student>();
      while(iter.hasNext()){
          Student stu=iter.next();
          mytree.add(stu);
      } 
     Iterator<Student> te=mytree.iterator();
      while(te.hasNext()) {
         Student stu=te.next(); 
        System.out.println(""+stu.name+" "+stu.english);
      }
   }
 }

Run the screenshot:

  • There are 10 USB sticks with two important attributes: price and capacity. Write an application that uses TreeMap.
import java.util.*; 
class UDiscKey implements Comparable {
     double key=0;
     UDiscKey(double d) {
      key=d;
    } 
   public int compareTo(Object b) {
      UDiscKey disc=(UDiscKey)b; 
     if((this.key-disc.key)==0)
         return -1;
      else 
        return (int)((this.key-disc.key)*1000);
   }
 } 
class UDisc{
      int amount;
     double price; 
    UDisc(int m,double e) {
        amount=m;
         price=e;
    }
 } 
public class E { 
   public static void main(String args[ ]) { 
      TreeMap<UDiscKey,UDisc>  treemap= new TreeMap<UDiscKey,UDisc>();
       int amount[]={1,2,4,8,16};
       double price[]={867,266,390,556};
       UDisc UDisc[]=new UDisc[4];
       for(int k=0;k<UDisc.length;k++) { 
         UDisc[k]=new UDisc(amount[k],price[k]);
       } 
      UDiscKey key[]=new UDiscKey[4];
        for(int k=0;k<key.length;k++) { 
         key[k]=new UDiscKey(UDisc[k].amount);        } 
      for(int k=0;k<UDisc.length;k++) { 
         treemap.put(key[k],UDisc[k]);                 } 
      int number=treemap.size(); 
      Collection<UDisc> collection=treemap.values();
       Iterator<UDisc> iter=collection.iterator();
       while(iter.hasNext()) {
          UDisc disc=iter.next(); 
         System.out.println(""+disc.amount+"G "+disc.price+"元");       } 
      treemap.clear(); 
      for(int k=0;k<key.length;k++) { 
 key[k]=new UDiscKey(UDisc[k].price);       } 
      for(int k=0;k<UDisc.length;k++) {
          treemap.put(key[k],UDisc[k]);       } 
      number=treemap.size();
       collection=treemap.values();
       iter=collection.iterator();
       while(iter.hasNext()) {
          UDisc disc=iter.next(); 
         System.out.println(""+disc.amount+"G "+disc.price+"元");
       }
     }
 }

Run the screenshot:

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325458295&siteId=291194637