java 练习(常用类)

Arrays自写排序(sort)

package com.atguigu.day20;

import java.util.Arrays;
import java.util.Comparator;

public class ArraysCommonMethods {
	public static void main(String[] args) {
		// sort 排序(自然排序和定制排序) Integer arr[] = {1, -1, 7, 0, 89};
		int[] arr = {1,-4,56,23,4};
		Arrays.sort(arr);
		System.out.println(Arrays.toString(arr));
		
		Integer[] arr2 = { 1, -2, 9, 8, 70 };// 现象
		//系统排序
		Arrays.sort(arr2, new Comparator<Integer>() {

			@Override
			public int compare(Integer o1, Integer o2) {
				// TODO Auto-generated method stub
				return o2 -o1;
			}
		});
		System.out.println(Arrays.toString(arr2));
		
		// 定制排序, 自己写
		//使用自己写的排序方法排序
		int [] arr3 = {1, 0, 89, -23, 90, 3};
		
		MyArrays.sort(arr3, new MyComparator() {
			
			@Override
			public int compare(int n1, int n2) {
				// TODO Auto-generated method stub
				return n1 - n2;
			}
		});
		System.out.println(Arrays.toString(arr3));  //升序
		//return n2 - n1 则就是降序
	}
}
//模拟一下是如何实现这个效果的.........
//使用冒泡完成
interface MyComparator{
	public int compare(int n1,  int n2);
}

class MyArrays {
	public static void sort(int[] arr,MyComparator myComparator){
		//冒泡
		int temp;
		for(int i =0 ; i< arr.length - 1; i++){
			for(int j =0; j<arr.length-1-i;j++){
				if (myComparator.compare(arr[j], arr[j + 1]) > 0) {
					// 交换
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1]= temp;
				}

			}
		}
	}
}

Arrays类的 binarySearch方法

//binarySearch 通过二分搜索法进行查找,要求必须排好序
		int [] arr4 = {1, 3, 9, 90, 120, 800};
		int index = Arrays.binarySearch(arr4, 100); //-5
		System.out.println("index=" + index); //index=-5
		/*
		 * 源码 (看不咋懂)
		 * public static int binarySearch(int[] a, int key) {
        return binarySearch0(a, 0, a.length, key);
        
        
        	源码往里追
        	private static int binarySearch0(int[] a, int fromIndex, int toIndex,
                                     int key) {
        int low = fromIndex;
        int high = toIndex - 1;

        while (low <= high) {
            int mid = (low + high) >>> 1;
            int midVal = a[mid];

            if (midVal < key)
                low = mid + 1;
            else if (midVal > key)
                high = mid - 1;
            else
                return mid; // key found
        }
        return -(low + 1);  // key not found.
    }
    }
		 */

Arrays类的 copyOf方法

//copyOf
		//数组元素的复制
		int [] arr5 = {1, 3, 8, 10};
		int[] newArr = Arrays.copyOf(arr5, 9);
		System.out.println("newArr=" + Arrays.toString(newArr));
		//newArr=[1, 3, 8, 10, 0, 0, 0, 0, 0]
		/*copyOf 源码
		 * public static int[] copyOf(int[] original, int newLength) {
        		int[] copy = new int[newLength]; //创建个新数组,长度为newLength
        		System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        		return copy;
    }
		 */

Arrays类的 fill方法

//fill 数组元素的填充 
		Integer[] num = new Integer[]{9,3,2};
		Arrays.fill(num, 6);
		System.out.println("num=" + Arrays.toString(num));
		//结果  num=[6, 6, 6]
		/*
		 * fill源码, 就是将元素 替换
		 * public static void fill(Object[] a, Object val) {
        		for (int i = 0, len = a.length; i < len; i++)
            		a[i] = val;
    }
		 */

Arrays类的equals方法

//equals 比较两个数组元素内容是否完全一致
		int [] arr6 = {1,2,3};
		int [] arr7 = {1,2,3};
		boolean b = Arrays.equals(arr6, arr7);
		System.out.println("b=" + b);  //b=true

		/*
		 *  public static boolean equals(int[] a, int[] a2) {
        if (a==a2)
            return true;
        if (a==null || a2==null)
            return false;

        int length = a.length;
        if (a2.length != length)
            return false;

        for (int i=0; i<length; i++)
            if (a[i] != a2[i])
                return false;

        return true;
    }

		 */

Arrays类的asList方法

/*
		 * asList 将一组值,转换成list List<Integer> asList = Arrays.asList(2,3,4,5,6,1);
		 * System.out.println("asList=" + asList);
		 */

		//将 2,3,4,5,6,1 => 转成 List 集合
		List<Integer> asList = Arrays.asList(2,3,4,5,6,1);
		System.out.println(asList);
		
		/*
		 * 源码
		 * @SafeVarargs
    @SuppressWarnings("varargs")  //抑制警告
    public static <T> List<T> asList(T... a) {  //可变参数
        return new ArrayList<>(a);
    }
		 */

练习题

package com.atguigu.day20;

import java.util.Arrays;
import java.util.Comparator;

public class ArrayExercise01 {
	public static void main(String[] args) {
		Book[] book = new Book[3];
		book[0] = new Book("水浒",23.2);
		book[1] = new Book("三国",12);
		book[2] = new Book("西游记",3.2);
		Arrays.sort(book,new Comparator<Book>() {

			@Override
			public int compare(Book o1, Book o2) {
				// TODO Auto-generated method stub
				if (o2.getPice() - o1.getPice() > 0) {
					return -1;
				} else if (o2.getPice() - o1.getPice() < 0) {
					return 1;
				} else {
					return 0;
				}

			}
		});
		System.out.println(Arrays.toString(book));
		
		Arrays.sort(book);
		System.out.println("books=" + Arrays.toString(book));

	}
}
//1)	自定义Book类,里面包含name和price,按price排序(从大到小)。
//要求使用两种方式排序 , 对对象的某个属性排序!!.


//解读
//1. Comparable 接口, 有 抽象方法 public int compareTo(T o);
//2. 我们需要实现 compareTo, 完成比较,同样,可以完成自定义的排序

class Book implements Comparable{
	private String name;
	private double pice;
	public Book(String name, double pice) {
		super();
		this.name = name;
		this.pice = pice;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPice() {
		return pice;
	}
	public void setPice(double pice) {
		this.pice = pice;
	}
	
	
	
	
	@Override
	public String toString() {
		return "Book [name=" + name + ", pice=" + pice + "]";
	}
	@Override
	public int compareTo(Object o) {
		// TODO Auto-generated method stub
		//比较 book 的价格
		//转成 book
		Book b = (Book)o;
		if(this.pice > b.pice){ //从小到大
			return -1;
		}else if(this.pice < b.pice){
			return 1;
		}else
			return 0;
	}
	
	
}

System 类的常用方法

package com.atguigu.day20;

import java.util.Arrays;

public class SystemCommonMethods {
	public static void main(String[] args) {
		//System 类
		
		//退出当前程序
		//System.exit(0);
		
		/*
		 * 2)	arraycopy :复制数组元素,比较适合底层调用,一般使用Arrays.copyOf完成复制数组.
				int[] src={1,2,3};
				int[] dest = new int[3];
				System.arraycopy(src, 0, dest, 0, 3);

		 */
		int[] src={1,2,3};
		int[] dest = new int[3];
		/*
		 * 说明
		 * 参数1. src 表示原数组
		 * 参数2. 0 表示从原数组哪个下标的开始
		 * 参数3. dest 拷贝到数组,目标数组
		 * 参数4. 0 表示拷贝到目标数组的哪个下标位置
		 * 参数5. 3 一共拷贝多少个
		 * 
		 */
		System.arraycopy(src, 0, dest, 0, 3);
		System.out.println("desc=" + Arrays.toString(dest));

		//currentTimeMillens 毫秒数 1970-1-1 0:0:0 到现在的
		
		System.out.println(System.currentTimeMillis());

	}
}

BigInteger和BigDecimal类

package com.atguigu.day20;

import java.math.BigDecimal;
import java.math.BigInteger;

public class BigIntegerDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		//一个数超过long的范围,我们就可以用BigInteger 表示
		BigInteger b1 = new BigInteger("19999999999999999999999999999999");
		BigInteger b2 = new BigInteger("200");
		// 2.调用常见的运算方法
		// System.out.println(b1+b2); 不能使用 这样的 + 方法运行
		
		//底层=>转成数组
//		System.out.println(b1.add(b2)); //加
//		System.out.println(b1.subtract(b2)); //减
//		System.out.println(b1.multiply(b2)); //乘
//		System.out.println(b1.divide(b2)); //除
//		
		BigDecimal b3 = new BigDecimal("188888888888888.999999999999999");
		BigDecimal b4 = new BigDecimal("3");
		System.out.println(b3.divide(b4, BigDecimal.ROUND_CEILING));// 除
		
	}

}

Date类

第一代日期

package com.atguigu.day20;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateG1Demo {
	public static void main(String[] args) throws ParseException {
		Date date = new Date(); //获取当前系统时间 美国
		Date date2 = new Date(2134534); //通过指定毫秒数得到时间美国
		
		System.out.println(date);
		System.out.println(date2);
		
		System.out.println(date.getTime());//获取某个时间对应的毫秒数1970-1-1
		
		//格式化
		//格式, 是根据自己需要来确定.
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日hh:mm:ss");
		String format = sdf.format(date);  // format:将日期转换成指定格式的字符串
		System.out.println(format);
		
		//比如我们知道一个字符串格式时间,可以反向得到 Date
		String s = "1996年01月01日 10:20:30 星期一";
		Date parse = sdf.parse(s);
		System.out.println(parse); //美国格式
	
	}
}

第二代日期

package com.atguigu.day20;

import java.util.Calendar;

public class DateG2Demo {
	public static void main(String[] args) {
		// 把需要的信息,都给到 Calendar, 程序员需要什么,自己组合
		Calendar c = Calendar.getInstance(); // 创建日历类对象//比较简单,自由
		System.out.println(c);

		//获取日历对象的某个字段n
		
		System.out.println("年:" + c.get(Calendar.YEAR));
		//注意 Calendar类 默认 MONTH(月) 是从0 开始
		System.out.println("月:" + c.get(Calendar.MONTH) + 1);
		System.out.println("日:" + c.get(Calendar.DAY_OF_MONTH));
		System.out.println("小时:" + c.get(Calendar.HOUR));
		System.out.println("分:" + c.get(Calendar.MINUTE));
		System.out.println("秒:" + c.get(Calendar.SECOND));
		
		System.out.println(c.get(Calendar.YEAR)
				+"年"+(c.get(Calendar.MONTH)+1)+"月"
				+c.get(Calendar.DAY_OF_MONTH)+"日");

		
	}
}

第三代日期

package com.atguigu.day20;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.MonthDay;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

import org.junit.Test;

public class DateAllMethods {
	public static void main(String[] args) {

	}

	// 测试LocalDate类
	@Test // 可以直接在方法上执行,不需要在mian函数调用 JUnit执行
	public void testLocalDate() {
		// 获取当前日期(只包含日期,不包含时间) //第三代
		LocalDate date = LocalDate.now();
		System.out.println(date);

		// 获取日期的指定部分
		System.out.println("year:" + date.getYear());
		System.out.println("month:" + date.getMonthValue());
		System.out.println("day:" + date.getDayOfMonth());
		System.out.println("week:" + date.getDayOfWeek());

		// 根据指定的日期参数,创建LocalDate对象
		LocalDate of = LocalDate.of(2014, 5, 23);
		System.out.println(of);
	}

	// 测试LocalTime类
	@Test
	public void testLocalTime() {
		LocalTime time = LocalTime.now();
		System.out.println(time);
		// 获取时间的指定部分
		System.out.println("hour:" + time.getHour());
		System.out.println("minute:" + time.getMinute());

		System.out.println("second:" + time.getSecond());
		System.out.println("nano:" + time.getNano());

		// 根据指定的时间参数,创建LocalTime对象
		LocalTime of = LocalTime.of(10, 20, 55);
		System.out.println(of);

	}

	// 测试LocalDateTime类
	@Test
	public void testLocalDateTime() {
		// 获取当前时间(包含时间+日期)

		LocalDateTime time = LocalDateTime.now();
		System.out.println(time);
		// 获取时间的指定部分
		System.out.println("year:" + time.getYear());
		System.out.println("month:" + time.getMonthValue());
		System.out.println("mouth:" + time.getMonth());
		System.out.println("day:" + time.getDayOfMonth());
		System.out.println("hour:" + time.getHour());
		System.out.println("minute:" + time.getMinute());

		System.out.println("second:" + time.getSecond());
		System.out.println("nano:" + time.getNano());

		// 根据指定的时间参数,创建LocalTime对象
		LocalDateTime of = LocalDateTime.of(2020, 2, 2, 10, 20, 55);
		System.out.println(of);

	}

	// 测试MonthDay类:检查重复事件
	@Test
	public void testMonthDay() {
		LocalDate birth = LocalDate.of(1990, 3, 10);
		MonthDay birthMonthDay = MonthDay.of(birth.getMonthValue(), birth.getDayOfMonth());

		LocalDate now = LocalDate.now();// 当前日期
		MonthDay current = MonthDay.from(now);// 通过 LocalDate 获取 月日
		System.out.println(current);
		// 我们的日期是可以相互比较的.
		if (birthMonthDay.equals(current)) {
			System.out.println("今天生日");
		} else {
			System.out.println("今天不生日");
		}

	}

	// 测试是否是闰年
	@Test
	public void testIsLeapYear() {

		LocalDate now = LocalDate.now(); // 日期

		System.out.println(now.isLeapYear());// 判断闰年

	}

	// 测试增加日期的某个部分, 对日期,进行修改
	@Test
	public void testPlusDate() {

		LocalDate now = LocalDate.now();

		LocalDate plusYears = now.plusWeeks(3);// 灵活...

		System.out.println(plusYears);

	}

	// 使用plus方法测试增加时间的某个部分
	@Test
	public void testPlusTime() {

		LocalTime now = LocalTime.now();
		LocalTime plusHours = now.plusHours(5);

		System.out.println(plusHours);

	}

	// 使用minus方法测试查看一年前和一年后的日期
	// 开发过程中,
	@Test
	public void testMinusTime() {
		LocalDate now = LocalDate.now();

		// 演示就是 在当前的日期基础上 减去1年
		// minus 减去 ChronoUnit.YEARS 单位
		LocalDate minus = now.minus(1, ChronoUnit.YEARS);
		System.out.println(minus);

		// LocalDate minus2 = now.minusYears(1);
		// System.out.println(minus2);

	}

	// 测试时间戳类:Instant ,相当于以前的Date类
	@Test
	public void testInstant() {
		// Instant 和 Date 相互
		Instant now = Instant.now();
		System.out.println(now);

		// 与Date类的转换
		Date date = Date.from(now);
		System.out.println(date);

		Instant instant = date.toInstant();

		System.out.println(instant);

	}

	// 测试DateTimeFormatter
	@Test
	public void testDateTimeFormatter() {

		// 第三代 DateTimeFormatter
		// 可以将 日期转成字符串
		DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MM-dd  HH:mm:ss");

		// 将字符串转换成日期

		// LocalDateTime parse = LocalDateTime.parse("03-03 2017 08:40:50",
		// pattern);
		// System.out.println(parse);

		// 将日期转换成字符串
		LocalDateTime now = LocalDateTime.now();
		String format = pattern.format(now);
		System.out.println("结果是=" + format);
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值