初学Java_方法总结(一)

来源:互联网 发布:mac yy服务器连接错误 编辑:程序博客网 时间:2024/06/05 20:30

1、数组排序

       在Java中对数组排序很容易,因为Arrays类提供了sort()这种方法实现这种功能。Arrays类位于java.util中,它可以对任何类型(包括字符串)的数组进行排序。

使用Arrays类的sort()方法对数组进行排序后,其中的值将按数字升序排列,字符和字符串将按字母顺序排列。

       

 String[] names = {"first" , "second" , "third" , "forth" , "fifth" , "sixth" , "seventh" , "eighth" , "ninth" , "tenth"};//        int[] names = {9 , 2 , 4 , 3 , 7 , 1 , 8 , 0 , 5 , 6};        System.out.println("原始排序:");        for (int i = 0; i < names.length; i++)         {            System.out.print(names[i] + " , ");        }        Arrays.sort(names);        System.out.println("\n" + "新排序");        for (int i = 0; i < names.length; i++)         {            System.out.print(names[i] + " , ");        }


 

2、在子类中使用this和super

       在子类中this和super是两个很有用的关键字。

       关键字this用于引用当前对象。创建类时,要引用根据该类创建的特定对象,可使用this,例如:

Public class test01{       int t;       Public test01(int a)       {              this.t = a;}}


       关键在super的用途类似:引用对象的上一级超类。可以以下面几种方式使用super:

       引用超类的变量,如super.name = “小武灵灵”;

       引用超类的方法,如super.move();

       引用超类的构造函数,如super(x, y);

下面是一个完整的例子:

public class Point3D extends Point{    public int z;    public Point3D(int x , int y , int z) {        super(x , y);        this.z = z;    }public void move(int x, int y , int z) {        this.z = z;        super.move(x, y);    }    public void translate(int x, int y , int z) {        this.z += z;        super.translate(x, y);    }}


我们在主函数中就可以这样使用它:

      

Public static void main(String[] args)       {              Point3D p = new Point3D(11 , 22 , 33);              p.move(33 , 22 , 11);}


       就相当于我们调用了point3D继承的Point的move(int x , int y)方法,又调用了point3D的move(int x , int y , int z)方法。

 

3、将相同类型的对象存储在Vector中

       Vector是一种存储相同类对象的数据结构,类似于数组,也存储相关的数据,但其长度可动态滴增减.

       Vector类位于java.util包中,这是Java类库中最有用的一个包。如果要使用它需要导入这个包:java.util.Vector。

       Vector存储的对象要么属于同一个类,要么有相同的超类,例如:

              Vector<String> vector = new Vector<String>();

       Vector默认长度为10,当然你也可以创建一个定长的Vector,例如:

              Vector<String> vector = new Vector<String>(100);

       Vector中的元素是根据添加的顺序排列的,第一个元素索引为0,向Vector中添加元素使用vector.add()方法;

       取得指定位置的元素用get(int index)方法;

       取得第一个元素用firstElement()方法;

       取得最后一个元素用lastElement()方法;

       删除指定位置的元素用remove(int index)方法;

       删除某元素用remove(object o)方法;

       判断是否包含某元素用contains(object o)方法;

       清空所有元素用clear()方法;

 

 

 

原创粉丝点击