201871010106- Ding Xuan Yuan "object-oriented programming (java)" twelfth week learning summary

                      201871010106- Ding Xuan Yuan "object-oriented programming (java)" twelfth week learning summary

Text at the beginning:

project

content

This work belongs courses

https://home.cnblogs.com/u/nwnu-daizh/

Where this requirement in the job

https://www.cnblogs.com/nwnu-daizh/p/11867214.html 

Job learning objectives

(1) master Vetor , Stack , the Hashtable three classes of common use and the API ;

(2) control the ArrayList , LinkList use two common classes and the API .

(3)  master the Java GUI framework to create and property of the commonly used class of API ;

(4) apply pair programming ( Pair Programming ), experience the program both in development cooperation .

Text content:

Part I: summary of the ninth, ten chapters of theoretical knowledge

   9-1 Java framework set: to achieve encapsulation of a variety of data structures

     1. Frame: a library

       Including some common interface and super classes, implement these interfaces or create these subclasses superclass can easily design programs required classes

     2. A set (container):  comprising a plurality of elements and to provide a method of operating the elements of the class included , the elements may be contained by the same type of object composition, it may also consist of different types of objects

     3. Collections Framework: Java collections library unified architecture

    4. action: (1) Java collection class provides support for basic data types eg: the Vector, the Hashtable, Stack

              (2) collection classes: collection classes comprising the introduction import.java.util * java.util package.

    5. Features: receiving objects only    

        Arrays can receive basic data types and data objects

    6. The old and new collections

      And in JDK1.1 Java1.0: the Vector (vector), Hashtable (hash table), Stack (Stack), Properties (attribute sets)

      a.Vector categories : variable-length array of similar objects can be stored, accessed by the subscript

        Key properties: capacity: set up to accommodate the number of elements

              capacityIncrement: How much capacity increments

             size: a collection of the current element

        The key method: void addElement (Object obj),

          void   add(int  index,  Object   element),

          Object  elementAt(int   index),

          void   insertElementAt(Object   obj,  int  index)

       B. Stack categories: a subclass of class Vectoe

             Stack class described stack data structure, i.e. FILO

            The key method: public void push (Object item)

               public  Object   pop() 

               public  Object  peek()

                 public    Boolean   empty()

      c. Hashtable class: to look through the key elements

            Hash code determined by the key. All objects have a hash code () can be obtained by a method hashCode Object class

    Java1.2: design of a unified set of classes: Collection,

                    List,

                    Set,

                    Map

  9-2 a set of basic interface framework

 

    

 

     1. Detailed:

      The root interface in the collection hierarchy: Collection

       Set: can not contain duplicate elements . Object may not be stored by the storage order, i.e. like an array can not be accessed by index manner, the SortedSet element is arranged in ascending order of a Set

       List: an ordered collection may contain duplicate elements, it provides a way of accessing by index

       Map: contains key-value pairs can not contain duplicate key

       SortedMap: a is in ascending order of the key Map.

       2. The set of framework classes:

 

 

    . A List: sequence element has a determined;

     Class ArrayListLinkedList, elements are sequentially stored in memory

      能够自动增长容量的数组,利用ArrayList的toArrY()返回一个数组

      Arrays.asList()返回一个列表

      类LinkedList,元素在内存中是链表方式存储

       采用双向循环链表实现的

      利用LinkedList实现栈,队列,双向队列,类内除了数据本身外,还有两个引用,分别指向前一个元素和后一个元素

        b.Set:必须定义equals方法,提供算法来判断欲添加进来的元素是否与已经存在的某对象相等

       实现Set接口的类:HashSet,TreeSet。

    c.TreeSet:一个有序集合

         元素按照升序排列,TreeSet中元素要实现Comparable接口

       在构造TreeSet对象时,传递实现了Comparable接口的比较器对象

       HashSet是基于Hash算法实现的,其性能通常都优于TreeSet,使用HashSet,需要排序的功能时,使用TreeSet。

    d.Map:用来处理”键—值“对,以便通过键值来查找相应的元素

         基于散列表实现(替代Hashtable)

         TreeMap在一个二叉树的基础上实现。

      1.定义:

         Map接口映射唯一关键字的值

        关键字(key):用于检索值得对象。

          给定一个关键字和值,可以存储这个值到一个Map对象中。

          当值被存储后,就可以使用关键字来检索它

       2.Map循环:get()

           put():可以将一个指定了”关键字和值“得值加入映射,为了得到值,可以将关键字作为参数来调用get()方法。

      3.方法:boolean   containsKey(Object   K) ;

           boolean   containsValue(Object  v)  ; 

          Object   get(Object  k) ;

          Boolean  isEmpty();

           Object   put(Object  k, Object  v)

           Object  remove (Object  k)  

       4.接口:实现类:HashMap、TreeMap、Hashtable、properties

     第九章总结:

      可以为大型,小型作业提供便利;

 

  第十章

    10-1AWT与Swing简介

     1.用户界面:用户与计算机系统(各种程序)交互的接口

          图形用户界面:以图形方式呈现的用户界面;

     2.AWT:

        Java的抽象窗口工具箱在java.util包中,提供了许多用来设计GUI的组件类和容器类;

        处理用户界面元素的方法:把图形元素的创建和行为委托给本地的GUI工具箱进行处理

        缺陷:菜单、滚动条、和文本域等用户界面元素,在不同的平台,操作行为存在一些微妙的差异。

     3.AWT组件

      4.Swing:具有更加丰富且方便的用户界面元素的集合;底层平台的依赖很少;Swing类库在javax.swing包里;组件层次关系      

     5.AWT与Swing的关系

         组件:构成图形用户界面的元素,用图形显示。

         通常把由Comparable类的子类后者间接子类创建的对象称为一个组件。

       6.容器:Java中能容纳和排列组件的组件

         a.常用的容器时框架:(Frame,JFrame)

            API:void   setResizable(boolean   b) ,

              void    set Title(String    s),

              void   setIconImage(Image  image)

         b.添加组件:Container类提供了方法add(),用来在容器类组件对象中添加其他组件

              eg:fra.add(button)

           可以把一个容器添加到另一个容器里,实现容器嵌套

     7.框架的创建(Frame)

        a.创建空框架:常采用框架创建初始界面,即GUI的顶层窗口

         b.框架定位于框架属性

            定位:用Component类的setLocation和setBounds方法

            属性:Title:框架标题

               IconImage:框架图标

         c.确定框架大小:调用Toolkit类的方法来得到屏幕尺寸信息

    8.在组件中显示信息:

      a.JFrame的结构:根面板、层级面板、玻璃面板和内容面板四层面板

        用户也可以自行创建一个组件类;此时需要重载paintComponent()

     *9.图形编程:2D图形   坐标系         图形类:

    10.颜色的使用:Graphics 2D类的setPaint方法

      a.标准色   

      b.复合色          

     11.字体的使用: (1)  AWT的五种逻辑字体名:SanaSerif      Serif     Monospaced    Dialog    Dialoginput

             (2)字体风格:Font.PLAIN        Font.BOLD     Font.ITALIC     Font.BOLD+Font.ITALIC

     12.图像:

       将一个图像文件加载到程序中,调用Graphics类提供的DrawImage()显示

         eg:

          public   void   paintComponent(Graphics  g)

           {   g.drawImage(image   x , y,null)}

 第二部分:实验内容和步骤

  实验1 导入第9章示例程序,测试程序并进行代码注释。

     测试程序1:

    使用JDK命令运行编辑、运行以下三个示例程序,结合运行结果理解程序;

     掌握VetorStackHashtable三个类的用途及常用API

    示例代码1:

//示例程序1
import java.util.Vector;
class Cat {
     private int catNumber;//Cat的私有属性catNumber
     Cat(int i) {
        catNumber = i;
     }
     void print() {
        System.out.println("Cat #" + catNumber);
     }
}
public class Cats{
    public static void main(String[] args){
       Vector<Cat> cats= new Vector<Cat>();
       for(int i=0; i<7; i++)      //for循环
           cats.addElement(new Cat(i)); 
       for(int i=0; i<cats.size(); i++)
           (cats.elementAt(i)).print();
   }
}

  结果:

 

 

   示例代码2:

//示例程序2
import java.util.*;
public class Stacks
{
   static String[] months={"金","银","铜","铁"};//字符串数组month
   public static void main(String[] args){
      Stack<String> stk = new Stack<String> ();
      for(int i=0; i<months.length; i++)
          stk.push(months[i]);   //入栈,即入栈顺序为金,银,铜,铁
      System.out.println(stk);
      System.out.println("element 2=" + stk.elementAt(2));//数组下标从0开始,故element 2应为铜
      while(!stk.empty())    //循环出栈,直至栈内元素为空
          System.out.println(stk.pop());//打印出栈元素,先入后出,即出栈的顺序为铁,铜,银,金
  }
}

  结果:

 

 

   示例代码3:

  

import java.util.*;
class Counter {
    int i = 1;//friendly
    public String toString() {//将其他类型的数据转换为字符串类型
        return Integer.toString(i);
    }
}

public class Statistics {
    public static void main(String[] args) {
        Hashtable ht = new Hashtable();//创建哈希表这个数据类型,名为ht
        for (int i = 0; i < 10000; i++) {
            Integer r = new Integer((int) (Math.random() * 20));//将自动生成的0—20的数强制类型转换为int
            if(ht.containsKey(r))   //判断r是否是哈希表中某个元素的键值
              ((Counter)ht.get(r)).i++;//是,则用get方法获得值,i++
            else
              ht.put(r, new Counter());
}
        System.out.println(ht);
    }
}

  结果:

 

 

    测试程序2

    使用JDK命令编辑运行ArrayListDemoLinkedListDemo两个程序,结合程序运行结果理解程序;

      ArrayListDemo

      代码:

 

import java.util.*;

public class ArrayListDemo {
    public static void main(String[] argv) {
        ArrayList al = new ArrayList();
        // Add lots of elements to the ArrayList...   在ArrayList中添加元素
        al.add(new Integer(11));//利用add方法
        al.add(new Integer(12));
        al.add(new Integer(13));
        al.add(new String("hello"));
        // First print them out using a for loop.
        System.out.println("Retrieving by index:");
        for (int i = 0; i < al.size(); i++) {//循环打印
            System.out.println("Element " + i + " = " + al.get(i));
        }
     }
}

 

    结果:

  LinkedListDemo

    代码:

import java.util.*;
public class LinkedListDemo {
    public static void main(String[] argv) {
        LinkedList l = new LinkedList();
        l.add(new Object());   //迭代对象生成器
        l.add("Hello");
        l.add("zhangsan");
        ListIterator li = l.listIterator(0);//通过迭代器生成对象产生方法hasNext返回
        while (li.hasNext())
            System.out.println(li.next());
        if (l.indexOf("Hello") < 0)   //判断元素是否在集合当中
            System.err.println("Lookup does not work");
        else
            System.err.println("Lookup works");
   }
}

  结果:

 

 

  Elipse环境下编辑运行调试教材360页程序9-1,结合程序运行结果理解程序;

   掌握ArrayListLinkList两个类的用途及常用API

  代码:

 

package linkedList;

import java.util.*;

/**
 * This program demonstrates operations on linked lists.
 * @version 1.12 2018-04-10
 * @author Cay Horstmann
 */
public class LinkedListTest
{
   public static void main(String[] args)
   {
      List<String> a = new LinkedList<String>();//创建泛型a链表
      a.add("Amy");
      a.add("Carl");
      a.add("Erica");

      List<String> b = new LinkedList<String>();//创建泛型b链表
      b.add("Bob");
      b.add("Doug");
      b.add("Frances");
      b.add("Gloria");

      // merge the words from b into a  合并a,b中的单词

      ListIterator<String> aIter = a.listIterator();
      Iterator<String> bIter = b.iterator();

      while (bIter.hasNext())
      {
         if (aIter.hasNext()) aIter.next();
         aIter.add(bIter.next());
      }

      System.out.println(a);

      // remove every second word from b   从第二个链表中每隔一个元素删除一个元素

      bIter = b.iterator();
      while (bIter.hasNext())
      {
         bIter.next(); // skip one element 跳到第一个元素   
         if (bIter.hasNext())
         {
            bIter.next(); // skip next element 跳到下一个元素   
            bIter.remove(); // remove that element
         }
      }

      System.out.println(b);

      // bulk operation: remove all words in b from a 批量操作: 删除从b到a的所有单词

      a.removeAll(b);

      System.out.println(a);
   }
}

 

  结果:

 

 

   

  实验2导入第10示例程序,测试程序并进行代码注释。

   测试程序1:

    运行下列程序,观察程序运行结果。

    代码:

 

package linkedList;
import javax.swing.*;
public class SimpleFrameTest
{
   public static void main(String[] args)
   {
     JFrame  frame = new JFrame(); //JFrame框架
     frame.setBounds(0, 0,300, 200);//setBounds方法,从左上角开始,width:300,height:200
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭框
     frame.setVisible(true);//窗口可见
   }
}

 

    结果:

 

  elipse IDE中调试运行教材407页程序10-1,结合程序运行结果理解程序;与上面程序对比,思考异同;

  掌握空框架创建方法;

  了解主线程与事件分派线程概念;

  掌握GUI顶层窗口创建技术。

    代码:

 

package simpleFrame;

import java.awt.*;
import javax.swing.*;

/**
 * @version 1.34 2018-04-10
 * @author Cay Horstmann
 */
public class SimpleFrameTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() ->   //lambda表达式
         {
            SimpleFrame frame = new SimpleFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭框
            frame.setVisible(true);//窗口可见
         });
   }
}

class SimpleFrame extends JFrame//SimpleFrame继承JFrame
{
   private static final int DEFAULT_WIDTH = 300;//常量
   private static final int DEFAULT_HEIGHT = 200;

   public SimpleFrame()
   {
      setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);//设置大小
   }
}

  结果:

 

  测试程序2

    elipse IDE中调试运行教材412页程序10-2,结合运行结果理解程序;

    掌握确定框架常用属性的设置方法。

  代码:

 

package sizedFrame;

import java.awt.*;
import javax.swing.*;

/**
 * @version 1.35 2018-04-10
 * @author Cay Horstmann
 */
public class SizedFrameTest
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() ->     //lambda表达式
         {
             JFrame frame = new SizedFrame();
            frame.setTitle("SizedFrame");//设置标题
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭
            frame.setVisible(true);//窗口可见
         });
   }
}

class SizedFrame extends JFrame//SizedFrame继承于JFrame
{
   public SizedFrame()
   {
      // get screen dimensions得到屏幕的大小

      Toolkit kit = Toolkit.getDefaultToolkit();
      Dimension screenSize = kit.getScreenSize();//以Dimension对象的形式返回屏幕的大小
      int screenHeight = screenSize.height;
      int screenWidth = screenSize.width;

      // set frame width, height and let platform pick screen location

      setSize(screenWidth / 2, screenHeight / 2);//将框架设置为屏幕大小的一半
      setLocationByPlatform(true);

      // set frame icon

      Image img = new ImageIcon("icon.gif").getImage();//提供图标
      setIconImage(img);      
   }
}

 

  结果:

 

  测试程序3

    在elipse IDE中调试运行教材418页程序10-3,结合运行结果理解程序;

     掌握在框架中添加组件;

    掌握自定义组件的用法。

  代码:

 

package notHelloWorld;

import javax.swing.*;
import java.awt.*;

/**
 * @version 1.34 2018-04-10
 * @author Cay Horstmann
 */
public class NotHelloWorld
{
   public static void main(String[] args)
   {
      EventQueue.invokeLater(() ->     //lambda表达式
         {
            JFrame frame = new NotHelloWorldFrame();
            frame.setTitle("NotHelloWorld");//标题为NotHelloWorld
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//设置关闭
            frame.setVisible(true);//可见
         });
   }
}

/**
 * A frame that contains a message panel.
 */
class NotHelloWorldFrame extends JFrame//NotHelloWorldFrame继承JFrame
{
   public NotHelloWorldFrame()
   {
      add(new NotHelloWorldComponent());//添加窗口
      pack();
   }
}

/**
 * A component that displays a message.
 */
class NotHelloWorldComponent extends JComponent//NotHelloWorldComponent继承JComponent
{
   public static final int MESSAGE_X = 75;
   public static final int MESSAGE_Y = 100;

   private static final int DEFAULT_WIDTH = 300;
   private static final int DEFAULT_HEIGHT = 200;

   public void paintComponent(Graphics g)//绘图
   {
      g.drawString("Not a Hello, World program", MESSAGE_X, MESSAGE_Y);
   }

   public Dimension getPreferredSize() 
   {  
      return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT); 
   }
}

 

  结果:

  

  关于结对编程:

    以下图片是一个结对编程场景:两位学习伙伴坐在一起,面对着同一台显示器,使用着同一键盘,同一个鼠标,他们一起思考问题,一起分析问题,一起编写程序。关于结对编程的阐述可参见以下链接:

     http://www.cnblogs.com/xinz/archive/2011/08/07/2130332.html,http://en.wikipedia.org/wiki/Pair_programming

     对于结对编程中代码设计规范的要求参考:http://www.cnblogs.com/xinz/archive/2011/11/20/2255971.html

    结对编程:一种敏捷软件开发的方法,两个程序员在一个计算机上共同工作。一个人输入代码,而另一个人审查他输入的每一行代码。输入代码的人称作驾驶员,审查代码的人称作观察员。观察员同时考虑工作的战略性方向,提出改进的意见,增加代码的健壮性。在写代码时,可以互相讨论,提供思路。

 

 三.实验总结

  通过本次实验,我了解了:1.Vetor、Stack、Hashtable三个类用途及API           2.ArrayList、LinkList类的用法

3.Java GUI中框架创建及简单属性设置

  本次实验以验证性实验为主,主要集中于加深对数据结构中常见类的用法和简单框架的构造,对简单的数据结构有了更进一步的理解。存在的问题是对Hashtable代码的理解有一些困难,还有lambda表达式不太理解,熟悉。在空闲时间我要把lambda表达式多下一些功夫再次理解。在理解书上代码后,尝试着在理解的基础上自己动手敲代码有困难,在写的过程中问题很多,有些问题看似明白了,实质上对本质还是不理解,致使写出来很空难,要多尝试多写写。其次对结对编程的要求和优点有了了解。

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/budinge/p/11865471.html