Java基础----其他类的总结(二) 以及内部类和匿名内部类

本文详细介绍了Java中常用的工具类,包括Arrays、System、StringBuffer、Integer、Date、DateFormat、Calendar等类的基本用法和常见操作,通过示例代码帮助读者理解和掌握。


                                         第六个:Arrays工具类的使用

 概述:Arrays是针对数组操作的工具类。里面都是静态方法。

  常见的成员方法:

       public  static String toString(数组):把数组变成字符串。

       public  static  void sort(数组):对数组进行排序。

       public  static   int binarySearch(int[] arr, int value):二分查找。

自己的一个练习:

*
 * Arrays:针对数组操作的工具类。排序和查找。
 * 
 *	功能:
 *	public static String toString(int[] a):把整型数组转变成字符串。
 *	public static void sort(int[] a):对数组进行排序
 *	public static int binarySearch(int[] a,int key):对数组进行二分查找。
 *
 *	练习:请自己写代码,测试这三个方法。
 */
public class ArraysDemo {
	public static void main(String[] args) {
		// 定义数组
		int[] arr = { 23, 84, 51, 72, 69 };

		// public static String toString(int[] a):把整型数组转变成字符串。
		String str = Arrays.toString(arr);
		System.out.println(str);

		// public static void sort(int[] a):对数组进行排序
		Arrays.sort(arr);
		System.out.println(Arrays.toString(arr));

		// public static int binarySearch(int[] a,int key):对数组进行二分查找。
		int[] arr2 = { 12, 23, 34, 45, 56, 67 };
		// 查找23的索引
		System.out.println(Arrays.binarySearch(arr2, 23));
		// 查找27的索引
		System.out.println(Arrays.binarySearch(arr2, 27));
	}
}

asList方法:将数组转换成list集合。

          String[] arr = {"abc","yy","ss"};

       List<String> list = Arrays.asList(arr);//将arr数组转成list集合。

将数组转换成集合,有什么好处呢?用aslist方法,将数组变成集合可以通过list集合中的方法来操作数组中的元素:isEmpty()、contains、indexOf、set; 

    注意(局限性):数组是固定长度,不可以使用集合对象增加或者删除等,会改变数组长度的功能方法。比如add、remove、clear。(会报不支持操作异常UnsupportedOperationException);

如果数组中存储的是引用数据类型,直接作为集合的元素可以直接用集合方法操作。

如果数组中存储的是基本数据类型,asList会将数组实体作为集合元素存在。

 

集合变数组:用的是Collection接口中的方法:toArray();

如果给toArray传递的指定类型的数据长度小于了集合的size,那么toArray方法,会自定再创建一个该类型的数据,长度为集合的size。

如果传递的指定的类型的数组的长度大于了集合的size,那么toArray方法,就不会创建新数组,直接使用该数组即可,并将集合中的元素存储到数组中,其他为存储元素的位置默认值null。所以,在传递指定类型数组时,最好的方式就是指定的长度和size相等的数组。

将集合变成数组后有什么好处?限定了对集合中的元素进行增删操作,只要获取这些元素即可


                                                                                      第七个:System常用方法使用

System,系统类,提供了静态的变量和方法供我们使用。

      成员方法:

                          public static void exit(int value):退出jvm,非0表示异常退出。
          public static long currentTimeMillis():返回当前系统时间的毫秒值。和1970 年 1 月 1 日午夜之间的时间差

                          public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length) :从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。

/*
 * System:System 类包含一些有用的类字段和方法。它不能被实例化。 
 * 
 * 成员方法:
 * 		public static void exit(int status):终止当前正在运行的 Java 虚拟机。参数用作状态码;根据惯例,非 0 的状态码表示异常终止。 
 * 		public static long currentTimeMillis():返回以毫秒为单位的当前时间。
 * 		public static void arraycopy(Object src,int srcPos,Object dest,int destPos,int length)
 * 		从指定源数组中复制一个数组,复制从指定的位置开始,到目标数组的指定位置结束。
 * 
 */
public class SystemDemo {
	public static void main(String[] args) {
		// public static void exit(int status)
		// System.exit(100);
		System.out.println("hello");

		// public static long currentTimeMillis():返回以毫秒为单位的当前时间。
		long time = System.currentTimeMillis();
		System.out.println(time);

		// 需求,请测试下面代码的运行时间
		// long start = System.currentTimeMillis();
		// for (int x = 0; x < 1000000; x++) {
		// System.out.println(x);
		// }
		// long end = System.currentTimeMillis();
		// System.out.println((end - start) + "毫秒");

		// public static void arraycopy(Object src,int srcPos,Object dest,int
		// destPos,int length)
		int[] arr = { 1, 2, 3, 4, 5 };
		int[] arr2 = { 5, 6, 7, 8, 9 };
		System.arraycopy(arr, 3, arr2, 3, 2);
		// System.arraycopy(arr, 4, arr2, 3, 2);

		System.out.println(Arrays.toString(arr));
		System.out.println(Arrays.toString(arr2));
	}
}

                                                                                              

                                                                                       第八个:StringBuffer类

StringBuffer类,字符串缓冲区类。个人理解就是字符个数可以改变的字符串类。

    (1)构造方法:A:StringBuffer()

                             B:StringBuffer(int  capacity)

                             C:StringBuffer(String str) 

     (2)成员方法:

                         A:添加功能

                                  public StringBuffer  append(int  i) :将int参数的字符串表示形式追加到此序列

                                  public  StringBuffer  insert(int  index,  int  i):在指定位置添加元素

                         B:删除功能

                                  StringBuffer  deleteCharAt(int  index):删除指定位置字符

                                  StringBuffer  delete(int start, int end): 删除指定开始位置和结束位置间的字符

                          C:替换功能

                                   StringBuffer   replace(int start ,int end,String str):把开始到结束位置的字符用一个新的字符串给替换。

                          D:截取功能

                                     String  substring(int start):从指定位置到末尾截取

                          E:反转功能

                                     StringBuffer   reverse():字符串反转

     (3)String 和StringBuffer的区别?

                 答:String 一旦被赋值,值不能发生改变。而StringBuffer的值还可以改变。因为StringBuffer采用的是缓冲区机制,一开始首先开辟一些空间,然后随着数据的增多,还可以继续不断开辟空间,这些操作针对的是同一个对象。

一个练习:键盘录入一个字符串,请把字符串的数据反转后输出。

/*
 * 需求:键盘录入一个字符串,请把字符串的数据反转后输出。
 * 
 * 举例:
 * 		输入:abc
 * 		结果:cba
 * 思路:结合所学知识点儿,有两种方法可以实现:
 * 方式1:
 * 		A:把字符串变成字符数组
 * 		B:数组倒着打
 * 方式2:
 * 		想使用StringBuffer的reverse()方法。
 * 		A:String -- StringBuffer	构造方法
 * 		B:StringBuffer -- reverse()
 * 		C:StringBuffer -- String	构造方法,toString()
 */
public class StringBufferTest {
	public static void main(String[] args) {
		// 方式1
		// Scanner sc = new Scanner(System.in);
		// System.out.println("请输入字符串:");
		// String line = sc.nextLine();
		// char[] chs = line.toCharArray();
		// for (int x = chs.length - 1; x >= 0; x--) {
		// System.out.print(chs[x]);
		// }

		// 方式2
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入字符串:");
		String line = sc.nextLine();

		StringBuffer sb = new StringBuffer(line);
		// 下面也可以
		// StringBuffer sb = new StringBuffer();
		// sb.append(line);
		sb.reverse();
		String result = new String(sb);
		// 下面这个也可以
		// String result = sb.toString();
		System.out.println(result);

		// 链式编程
		// String result2 = new StringBuffer(line).reverse().toString();
		// System.out.println(result2);
	}
}

                                                                            

                                                                              第九个:Integer类(基本类型包装类)


 说Integer类之前先说一下基本类型包装类。


  (1) 基本类型包装类概述(我自己的理解):基本类型的数据我们只能使用值,不能做更多的操作。为了方便我们操作,java就把每一种基本类型进行了包装,提供方法供我们使用。

    基本类型   和   包装类的对应关系

              byte                  Byte

              short                 Short 

               int                     Integer

               long                 Long

                   flooat                Float

                    double              Double

               char                   Char

                   boolean                Boolean          


下面以Integer举例讲解。

(2)下面是两个常用的构造方法:

                     A:Integer i = new Integer(int num);
     B:Integer i = new Integer(String s);


注意:s必须是一个由数字字符组成的字符串。

public class IntegerDemo2 {
	public static void main(String[] args) {
		// 把int类型变成Integer类型
		int num = 100;
		Integer i = new Integer(num);
		System.out.println(i.toString());

		// 把String类型变成Integer类型
		String s = "100";
		// String s = "100abc";   这样会报错
		// NumberFormatException:数据格式化异常
		Integer ii = new Integer(s);
		System.out.println(ii);
	}
}
(3)String 和 int 类型的转换
    A:String ---- int

                  Integer:public  static  int  parseInt(String  s) 

   B :int  ------  String

                 Integer:public static   String  toString (int   i)

                 String :public  static   String  valueOf(int  i)

/*
 * 我要判断某个数据是否在int范围内,请问怎么做?
 * 思路:把int范围的最大值和最小值找到,然后判断即可。
 * public static double pow(double a,double b)
 * 
 * public static final int MAX_VALUE
 * public static final int MIN_VALUE
 * 
 * if(num>=Integer.MIN_VALUE && num<=MAX_VALUE)
 * {
 * 		是int范围的。
 * }
 * 
 * 我们的基本数据类型,只有值的使用,为了能够进行更多的操作,比如说,某种基本类型的范围判断,整数的进制转换。
 * 那么,java就针对每种基本类型提供了一种包装类来使用。
 * 
 */
public class IntegerDemo {
	public static void main(String[] args) {
		// public static String toBinaryString(int i)
		// public static String toHexString(int i)
		// public static String toOctalString(int i)

		// 把60转变成二进制,八进制,十六进制
		System.out.println(Integer.toBinaryString(60));// 111100
		System.out.println(Integer.toOctalString(60));// 74
		System.out.println(Integer.toHexString(60));// 3c
	}
}
(4)JDK以后的新特性

      A:自动装箱      基本类型  ----  引用类型

      B:自动拆箱     引用类型  -----  基本类型 
           举例:

                     Integer   i=50;

                                  i+=100;

/*
 * JDK5以后新特性:
 * 自动装箱:也就是把基本类型直接赋值给引用类型。
 * 自动拆箱:也就是把引用类型直接拆成基本类型。
 * 
 * 开发原则:
 * 		只要是对象,就先做不为null判断。
 * 
 * 		Person p = ?; 传递的参数
 * 
 * 		if(p!=null)
 * 		{
 * 			p.show();
 * 		}
 */
public class IntegerDemo {
	public static void main(String[] args) {
		// 创建对象
		// Integer i = new Integer(100);
		Integer ii = 100;// 默认相当于new Integer(100)

		ii = ii + 200;
		// 等价于
		// ii = new Integer(ii.intValue()+200);
		/*
		 * 数据参与运算,要求类型一致。 而现在ii是Integer类型,200是int类型。 底层调用的是intValue()方法。
		 * 也就是说:ii+200 其实是:ii.intValue()+200 计算完毕后值是300。 最后又做了一次装箱操作。
		 */
		System.out.println(ii);

		// 看一个现象
		Integer i = null;
		// NullPointerException
		// i = i + 100
		// i = i.intValue() + 100
//		if (i != null) {
//			i += 100;
//			System.out.println(i);
//		}
		
		i += 100;
	}
}
 一道面试题:

/*
 * 关于Integer的面试题:
 * 		byte常量池。
 * 		也就是byte范围内的值,直接赋值给Integer,是从常量池里面获取的。
 */
public class IntegerTest {
	public static void main(String[] args) {
		Integer i1 = new Integer(127);
		Integer i2 = new Integer(127);
		System.out.println(i1 == i2);// false
		System.out.println(i1.equals(i2));// true

		Integer i3 = new Integer(128);
		Integer i4 = new Integer(128);
		System.out.println(i3 == i4);// false
		System.out.println(i3.equals(i4));// true

		Integer i5 = 128;
		Integer i6 = 128;
		System.out.println(i5 == i6);// false
		System.out.println(i5.equals(i6));// true

		Integer i7 = 127;
		Integer i8 = 127;
		System.out.println(i7 == i8);// true
		System.out.println(i7.equals(i8));// true
	}
}


(5)案例:

       把字符串中的数字字符排序。
       需求:"23 98 16 38 42"
       结果:"16 23 38 42 98"

/*
 * 需求:
 * 		我现在有一个字符串"23 98 71 54 60"
 * 		请你先办法,把这个字符串变成如下字符串:
 * 				   "23 54 60 71 98"
 * 
 * 思路:
 * 		A:字符串 -- 字符串数组
 * 		B:字符串数组 -- int数组
 * 		C:int[]排序
 * 		D:把排序后的int[] -- String
 */
public class StringTest {
	public static void main(String[] args) {
		String s = "23 98 71 54 60";

		// 字符串 -- 字符串数组
		String[] strArray = s.split(" ");

		// 字符串数组 -- int数组
		int[] arr = new int[strArray.length];

		// 循环遍历赋值
		for (int x = 0; x < arr.length; x++) {
			arr[x] = Integer.parseInt(strArray[x]);
		}
		
		//int[]排序
		Arrays.sort(arr);
		
		//把排序后的int[] -- String
		StringBuffer sb = new StringBuffer();
		for(int x=0; x<arr.length ;x++){
			sb.append(arr[x]).append(" ");
		}
		String result = sb.toString().trim();
		System.out.println(result);
		
	}
}

                                                                                          

                                                      第十个:Date类

   概述:Date类从Java开发包(JDK)1.0就开始进化,当时它只包含了几个取得或者设置一个日期数据的各个部分的方法,比如说年月日。这些方法现在遭到了批评并且已经被转移到了Calendar类里去了,我们将在本文中进一步讨论它。这种改进旨在更好的处理日期数据的国际化格式. 就象在JDK 1.1中一样, Date 类实际上只是一个包裹类, 它包含的是一个长整型数据, 表示的是从GMT(格林尼治标准时间)1970年, 1 月 1日00:00:00这一刻之前或者是之后经历的毫秒数。 
      Date类表示特定的瞬间,精确到毫秒。

构造方法:

                      Date():默认指当前系统时间。

                      Date(long  time):根据给定的毫秒值生成一个时间。


成员方法:

                     public  long  getTime():

                     public void setTime(long  time):
Date--- long    通过日期获取毫秒值

                          Date   d=new   Date();

                          long    time=d.getTime();

long ----   Date   通过毫秒值得到日期对象

                            long time =???;

                            Date    d=new  Date(time);

                            

                             Date   d2=new  Date();

                              d2.setTime(time);

                                                                                           

                                      第十一个:DateFormat 类

DateFormat :对日期进行格式化的类,提供了对日期进行格式化,和对字符串进行解析的功能。

Date ------ String  

                              public final String format(Date date)
              需要自己指定格式,常见的格式:
   yyyy年MM月dd日 HH:mm:ss
   yyyy年MM月dd日
   HH:mm:ss

yyyy-MM-dd HH:mm:ss
String -- Date
public Date parse(String source)
注意:如果是字符串到日期,你指定的格式必须和字符串的格式匹配。

  2013-12-12
         yyyy-MM-dd
  
         2013/11/11
    yyyy/MM/dd     

public class DateFormatDemo {
	public static void main(String[] args) throws ParseException {
		//从Date--String
		// 创建日期对象
		Date d = new Date();
		// Sat Dec 21 16:16:40 CST 2013
		// System.out.println(d);
		// 创建格式对象
		// DateFormat df = new SimpleDateFormat();//多态
		// SimpleDateFormat sdf = new SimpleDateFormat();// 用默认的模式
		// 默认模式不是我们想要的,所以,我们要指定模式
		// 怎么指定模式,获取说,这个模式是什么样子的?
		//2013年12月21日 16:23:34
		//yyyy年MM月dd日 HH:mm:ss
		//SimpleDateFormat(String pattern) 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
		String str = sdf.format(d);
		System.out.println(str);
		System.out.println("************");
		
		//从String--Date
		String s = "2013-12-12 23:12:34";
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date dd = sdf2.parse(s);
		System.out.println(dd);
	}
}

                                                                                                                                 

                                                第十二个:Calendar类

Calendar是日历类,它可以获取任意指定日历值,然后自由组合。

成员方法:

                get(日历字段):根据给定的日历字段获取值

                set(年,月,日):给日历设定指定的年,月,日

                add(日历字段,值):给指定的日历字段添加或者减去给定的值。取决于值的正负。

/*
 * 请说出任意一年的2月份是多少天。
 */
public class CalendarDemo2 {
	public static void main(String[] args) {
		// 获取Calendar对象
		Calendar c = Calendar.getInstance(); //使用默认时区和语言环境获得一个日历。
		// public final void set(int year,int month,int date)
		// 注意,这里给的2其实是3月份。
		// c.set(2013, 2, 3);
		// 2013,3,3

		// public abstract void add(int field,
		// int amount)根据日历的规则,为给定的日历字段添加或减去指定的时间量。
		// c.add(Calendar.MONTH,2);
		// c.add(Calendar.DATE, -20);
		
		Scanner sc = new Scanner(System.in);
		int year = sc.nextInt();

		c.set(year, 2, 1);// 把日期设置为2013年3月1日
		c.add(Calendar.DATE, -1);// 把日期往前推1日

//		System.out.println(c.get(Calendar.YEAR));
//		System.out.println(c.get(Calendar.MONTH) + 1);
		System.out.println(c.get(Calendar.DATE));
	}
}

                                                                                                  

                                           第十三:内部类与匿名内部类


内部类定义:将一个类定义在另一个类里面,对里面那个类就称为内部类(内置类   嵌套类)

   (1)访问特点:

                    A:内部类可以直接访问外部类成员,包括私有
    B:外部类要想访问内部类成员,必须创建对象。

  (2)内部类分类:

                   A:成员位置  private  安全

                                            static     方便调用

                   B:局部位置    定义在方法中

                                              局部内部类访问局部变量必须加final修饰。

                                             延迟生命周期。

匿名内部类:是定义在局部位置的没有名字的内部类。

  A:前提是必须存在一个类,抽象类或接口

  B:格式
new 类或者接口名()
{
重写方法;
}


本质理解:其实这是一个继承类或者实现接口的匿名的子类对象。


C:使用
当你看到方法的形式参数是接口或者抽象类的时候。
用匿名内部类改进。(集合,IO,awt)



                          有些的不好的地方,真的希望大家能帮我指正!  先谢谢啦!!!


                        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值