Java个人笔记

HashSet 无序唯一,TreeSet 有序唯一

TreeSet 对一个实体类进行排序

HashSet<NavigationTable> navigationTableHashSet = new HashSet<>();
	....省略(导航栏代码)
TreeSet<NavigationTable> youxu = new TreeSet<>(navigationTableHashSet);

------------------------------
实体类
public class NavigationTable implements Comparable<NavigationTable> {
	.....省略实体
	
@Override           //对实体类的id进行排序
	public int compareTo(NavigationTable o) {
		int a = this.getId() - o.getId();
		return a;
	}
}

Java中Double保留后小数位的几种方法

Java中Double保留后小数位的几种方法网页地址

java获取当天,前天,明天,本周,本月,本年的开始日期时间和结束日期时间

java获取当天,前天,明天,本周,本月,本年的开始日期时间和结束日期时间

Math

  1. 舍掉小数取整:Math.floor(3.5)=3
  2. 四舍五入取整:Math.rint(3.5)=4
  3. 进位取整:Math.ceil(3.1)=4
  4. 取绝对值:Math.abs(-3.5)=3.5
  5. 取余数:A%B = 余数

迭代器

Iterator it = jsonObject.entrySet().iterator();
List<String> zgBm = new ArrayList<>();
while (it.hasNext()) {
    Map.Entry entry = (Map.Entry) it.next();
    if (entry.getValue().toString().equals("true")) {
        zgBm.add(entry.getKey().toString());
    }
}

local日期常用方法

getYear()    int    获取当前日期的年份
getMonth()    Month    获取当前日期的月份对象
getMonthValue()    int    获取当前日期是第几月
getDayOfWeek()    DayOfWeek    表示该对象表示的日期是星期几
getDayOfMonth()    int    表示该对象表示的日期是这个月第几天
getDayOfYear()    int    表示该对象表示的日期是今年第几天
withYear(int year)    LocalDate    修改当前对象的年份
withMonth(int month)    LocalDate    修改当前对象的月份
withDayOfMonth(int dayOfMonth)    LocalDate    修改当前对象在当月的日期
isLeapYear()    boolean    是否是闰年
lengthOfMonth()    int    这个月有多少天
lengthOfYear()    int    该对象表示的年份有多少天(365或者366)
plusYears(long yearsToAdd)    LocalDate    当前对象增加指定的年份数
plusMonths(long monthsToAdd)    LocalDate    当前对象增加指定的月份数
plusWeeks(long weeksToAdd)    LocalDate    当前对象增加指定的周数
plusDays(long daysToAdd)    LocalDate    当前对象增加指定的天数
minusYears(long yearsToSubtract)    LocalDate    当前对象减去指定的年数
minusMonths(long monthsToSubtract)    LocalDate    当前对象减去注定的月数
minusWeeks(long weeksToSubtract)    LocalDate    当前对象减去指定的周数
minusDays(long daysToSubtract)    LocalDate    当前对象减去指定的天数
compareTo(ChronoLocalDate other)    int    比较当前对象和other对象在时间上的大小,返回值如果为正,则当前对象时间较晚,
isBefore(ChronoLocalDate other)    boolean    比较当前对象日期是否在other对象日期之前
isAfter(ChronoLocalDate other)    boolean    比较当前对象日期是否在other对象日期之后
isEqual(ChronoLocalDate other)    boolean    比较两个日期对象是否相等


// 获取今天的日期
LocalDate now = LocalDate.now();
// 今天是几号
int dayofMonth = now .getDayOfMonth();
// 今天是周几(返回的是个枚举类型,需要再getValue())
int dayofWeek = now .getDayOfWeek().getValue();
// 今年是哪一年
int dayofYear = now .getDayOfYear();
// 取本月第1天:
LocalDate firstDayOfThisMonth=now .with(TemporalAdjusters.firstDayOfMonth()); 
// 取本月第2天:
LocalDate secondDayOfThisMonth = now .withDayOfMonth(2);
// 取本月最后一天,再也不用计算是28,29,30还是31:
LocalDate lastDayOfMonth=now .with(TemporalAdjusters.lastDayOfMonth()); 
// 取下一天:
LocalDate firstDayOfNextMonth = lastDayOfMonth.plusDays(1);
// 取2019年1月第一个周一:
LocalDate firstMondayOf2017 = LocalDate.parse("2019-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)); 
//本月的第一天
LocalDate monthFirstDay = LocalDate.of(now.getYear(),now.getMonth(),1);
 //本月的最后一天
LocalDate monthLastDay =now.with(TemporalAdjusters.lastDayOfMonth());
//上月的第一天
LocalDate date = now.minusMonths(1).withDayOfMonth(1);
//上月的最后一天
LocalDate date1 = date.with(TemporalAdjusters.lastDayOfMonth());

LocalDateTime

LocalDateTime now = LocalDateTime.now();
System.out.println("计算两个时间的差:");
LocalDateTime end = LocalDateTime.now();
Duration duration = Duration.between(now,end);
long days = duration.toDays(); //相差的天数
long hours = duration.toHours();//相差的小时数
long minutes = duration.toMinutes();//相差的分钟数
long millis = duration.toMillis();//相差毫秒数
long nanos = duration.toNanos();//相差的纳秒数
System.out.println(now);
System.out.println(end);

System.out.println("发送短信耗时【 "+days+"天:"+hours+" 小时:"+minutes+" 分钟:"+millis+" 毫秒:"+nanos+" 纳秒】");


//计算两个日期之间是的差额
LocalDate localDate = LocalDate.now();
LocalDate localDate2 = localDate.minusYears(5).minusMonths(10).minusDays(2);
Period next = Period.between(localDate2,localDate);
log.info("---------------年--------------------");
log.info(String.valueOf(next.getYears()));
log.info("---------------月--------------------");
log.info(String.valueOf(next.getMonths()));
log.info("----------------天-------------------");
log.info(String.valueOf(next.getDays()));

校验身份证

//校验身份证
    final static Map<Integer, String> zoneNum = new HashMap<>();
    final static int[] PARITYBIT = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
    final static int[] POWER_LIST = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10,
            5, 8, 4, 2};
    static {
        zoneNum.put(11, "北京");
        zoneNum.put(12, "天津");
        zoneNum.put(13, "河北");
        zoneNum.put(14, "山西");
        zoneNum.put(15, "内蒙古");
        zoneNum.put(21, "辽宁");
        zoneNum.put(22, "吉林");
        zoneNum.put(23, "黑龙江");
        zoneNum.put(31, "上海");
        zoneNum.put(32, "江苏");
        zoneNum.put(33, "浙江");
        zoneNum.put(34, "安徽");
        zoneNum.put(35, "福建");
        zoneNum.put(36, "江西");
        zoneNum.put(37, "山东");
        zoneNum.put(41, "河南");
        zoneNum.put(42, "湖北");
        zoneNum.put(43, "湖南");
        zoneNum.put(44, "广东");
        zoneNum.put(45, "广西");
        zoneNum.put(46, "海南");
        zoneNum.put(50, "重庆");
        zoneNum.put(51, "四川");
        zoneNum.put(52, "贵州");
        zoneNum.put(53, "云南");
        zoneNum.put(54, "西藏");
        zoneNum.put(61, "陕西");
        zoneNum.put(62, "甘肃");
        zoneNum.put(63, "青海");
        zoneNum.put(64, "新疆");
        zoneNum.put(71, "台湾");
        zoneNum.put(81, "香港");
        zoneNum.put(82, "澳门");
        zoneNum.put(91, "外国");
    }
    /**
     * @Description: 校验身份证是否合法
     * @Param: [certNo]
     * @return: boolean
     * @Author: 刘俊秦
     * @Date: 2019/6/3 0003
     */
    public static boolean isIDCard(String certNo) {
        if (certNo == null || (certNo.length() != 15 && certNo.length() != 18))
            return false;
        final char[] cs = certNo.toUpperCase().toCharArray();
        //校验位数
        int power = 0;
        for (int i = 0; i < cs.length; i++) {
            if (i == cs.length - 1 && cs[i] == 'X')
                break;//最后一位可以 是X或x
            if (cs[i] < '0' || cs[i] > '9')
                return false;
            if (i < cs.length - 1) {
                power += (cs[i] - '0') * POWER_LIST[i];
            }
        }

        //校验区位码
        if (!zoneNum.containsKey(Integer.valueOf(certNo.substring(0, 2)))) {
            return false;
        }

        //校验年份
        String year = certNo.length() == 15 ? getIdcardCalendar() + certNo.substring(6, 8) : certNo.substring(6, 10);

        final int iyear = Integer.parseInt(year);
        if (iyear < 1900 || iyear > Calendar.getInstance().get(Calendar.YEAR))
            return false;//1900年的PASS,超过今年的PASS

        //校验月份
        String month = certNo.length() == 15 ? certNo.substring(8, 10) : certNo.substring(10, 12);
        final int imonth = Integer.parseInt(month);
        if (imonth < 1 || imonth > 12) {
            return false;
        }

        //校验天数
        String day = certNo.length() == 15 ? certNo.substring(10, 12) : certNo.substring(12, 14);
        final int iday = Integer.parseInt(day);
        if (iday < 1 || iday > 31)
            return false;

        //校验"校验码"
        if (certNo.length() == 15)
            return true;
        return cs[cs.length - 1] == PARITYBIT[power % 11];
    }

    private static int getIdcardCalendar() {
        GregorianCalendar curDay = new GregorianCalendar();
        int curYear = curDay.get(Calendar.YEAR);
        int year2bit = Integer.parseInt(String.valueOf(curYear).substring(2));
        return year2bit;
    }

根据身份证号计算年龄

 /**
     * @Description: 根据身份证号计算年龄
     * @Param: [pensonnelIdCard]
     * @return: java.lang.Integer
     * @Author: 刘俊秦
     * @Date: 2019/6/3 0003
     */
    public static Integer getPersonAgeFromIdCard(String pensonnelIdCard) {

        //截取身份证中出行人出生日期中的年、月、日
        Integer personYear = Integer.parseInt(pensonnelIdCard.substring(6, 10));
        Integer personMonth = Integer.parseInt(pensonnelIdCard.substring(10, 12));
        Integer personDay = Integer.parseInt(pensonnelIdCard.substring(12, 14));

        Calendar cal = Calendar.getInstance();
        // 得到当前时间的年、月、日
        Integer yearNow = cal.get(Calendar.YEAR);
        Integer monthNow = cal.get(Calendar.MONTH) + 1;
        Integer dayNow = cal.get(Calendar.DATE);

        // 用当前年月日减去生日年月日
        Integer yearMinus = yearNow - personYear;
        Integer monthMinus = monthNow - personMonth;
        Integer dayMinus = dayNow - personDay;

        Integer age = yearMinus; //先大致赋值

        if (yearMinus == 0) { //出生年份为当前年份 
            age = 0;
        } else { //出生年份大于当前年份
            if (monthMinus < 0) {//出生月份小于当前月份时,还没满周岁
                age = age - 1;
            }
            if (monthMinus == 0) {//当前月份为出生月份时,判断日期
                if (dayMinus < 0) {//出生日期小于当前月份时,没满周岁
                    age = age - 1;
                }
            }
        }
        return age;
    }

java14 环境变量配置

win10 jdk14 配置已经不需要 jre 和 class_home了

JAVA_HOME    E:\JAVA\jdk-14
Path   %JAVA_HOME%\bin

centos jdk14 环境变量配置

#编写文件
vim  /etc/profile
#使配置文件生效
source /etc/profile
JAVA_HOME=/usr/local/java/jdk-14
export PATH=$JAVA_HOME/bin:$PATH

枚举enum的使用(与在switch中的使用)

看看枚举类

/**
 * 操作码类
 * @author kokJuis
 * @version 1.0
 * @date 2017-3-6
 */
public enum Code {
 
    SUCCESS(10000, "操作成功"), 
    FAIL(10001, "操作失败"), 
 
 
    private int code;
    private String msg;
 
    //为了更好的返回代号和说明,必须呀重写构造方法
    private Code(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
 
    public int getCode() {
        return code;
    }
 
    public void setCode(int code) {
        this.code = code;
    }
 
    public String getMsg() {
        return msg;
    }
 
    public void setMsg(String msg) {
        this.msg = msg;
    }
 
    
    // 根据value返回枚举类型,主要在switch中使用
    public static Code getByValue(int value) {
        for (Code code : values()) {
            if (code.getCode() == value) {
                return code;
            }
        }
        return null;
    }
    
}

使用:

//获取代码
int code=Code.SUCCESS.getCode();
//获取代码对应的信息
String msg=Code.SUCCESS.getMsg();
 
//在switch中使用通常需要先获取枚举类型才判断,因为case中是常量或者int、byte、short、char,写其他代码编译是不通过的
 
int code=Code.SUCCESS.getCode();
 
switch (Code.getByValue(code)) {
 
    case SUCCESS:
        //......
    break;
 
    case FAIL:
        //......
    break;
 
}

数组和集合中行列互换的解法

分析过程

  • 主对角线是保持不变
  • 行列互换即角标互换:[0][1] => [1][0]
  • 循环次数:外层循环行,内层循环每一行的列

示意图
在这里插入图片描述


//数组的情况
int arry[][] = new int[][] {{1,2,3},{4,5,6},{7,8,9}};
//这里arry为什么要减一呢,因为对角线是不用换的,所有去掉最后一次循环
for(int i=0; i< arry.length-1; i++) {
			//列循环从:i+1开始,提高循环效率
	for(int j=i+1; j< arry[i].length; j++) {
			int temp = arry[i][j];
			arry[i][j] = arry[j][i];
			arry[j][i] = temp;
	}
}

//集合的情况(具体数值就比列举了,和数值差不多)
for (var i = 0; i < arr.size() - 1; i++) {
    for (var j = i + 1; j < arr.get(i).size(); j++) {
            int temp = arr.get(i).get(j);
            arr.get(i).set(j, arr.get(j).get(i));
            arr.get(j).set(i, temp);
     }
 }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章