美文网首页
1 java常用类,枚举和注解

1 java常用类,枚举和注解

作者: Teemo_fca4 | 来源:发表于2019-05-23 09:45 被阅读0次

String 中通过字面量来初始化的时候,都会将值存储到常量池中,常量池是不会存储相同内容字符串的,
当对字符串引用重新赋值,连接操作或 调用replace方法时,如果常量池不存在新的内容,那么都需要重新存储字符串到常量池中,而不是在原来的字符串上修改内容。

    @Test
    public void test1() {
        String s1="abc";
        String s2="abc";
        System.out.println(s1==s2);//true
        s1="hello";
        System.out.println(s1==s2);//false
        System.out.println(s1);//hello
        System.out.println(s2);//abc
        System.out.println("*********************");
        String s3 = "abc";
        String s4 =s3+"def";
        System.out.println(s4);//abcdef
        System.out.println(s3);//abc
        System.out.println("*********************");
        
        String s5 = "abc";
        String s6 = s5.replace("a", "m");
        System.out.println(s5);//abc
        System.out.println(s6);//mbc
    }

String 通过new 来初始化的时候,对象是存储到堆里的,与字面量方式初始化不一样

    @Test
    public void test2() {
        String s1="abc";
        String s2="abc";
        String s3 = new String("abc");
        String s4 = new String("abc");
        System.out.println(s1==s2); //true
        System.out.println(s3==s4); // false
        System.out.println(s1==s3);// false
        String str = new String("s");//这个时候内存中新建了两个对象,一个是堆中的对象,一个是常量池对象(如果s之前不在常量池的情况)
    }

常量与常量之间的连接 结果还是在常量存储,只要有变量参与的+号赋值 结果是用过堆来存储(也适用于+=)

    @Test
    public void test3(){
        String s1 = "javaEE";
        String s2 = "hadoop";

        String s3 = "javaEEhadoop";
        String s4 = "javaEE" + "hadoop";
        String s5 = s1 + "hadoop";
        String s6 = "javaEE" + s2;
        String s7 = s1 + s2;

        System.out.println(s3 == s4);//true
        System.out.println(s3 == s5);//false
        System.out.println(s3 == s6);//false
        System.out.println(s3 == s7);//false
        System.out.println(s5 == s6);//false
        System.out.println(s5 == s7);//false
        System.out.println(s6 == s7);//false

        String s8 = s6.intern();//返回值得到的s8使用的常量值中已经存在的“javaEEhadoop”
        System.out.println(s3 == s8);//true
        
        final String s9 = "javaEE";//s4:常量 final修饰后 s9就是常量
        String s10 = s9 + "hadoop";
        String s11 = "javaEEhadoop";
        System.out.println(s11 == s10);//true
    }

String、StringBuffer、StringBuilder三者的异同?
String:不可变的字符序列;底层使用char[]存储
StringBuffer:可变的字符序列;线程安全的,效率低;底层使用char[]存储
StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;底层使用char[]存储
源码分析:

String str = new String();//char[] value = new char[0];
String str1 = new String("abc");//char[] value = new char[]{'a','b','c'};

StringBuffer sb1 = new StringBuffer();//char[] value = new char[16];底层创建了一个长度是16的数组。
System.out.println(sb1.length());//0
sb1.append('a');//value[0] = 'a';
sb1.append('b');//value[1] = 'b';
StringBuffer sb2 = new StringBuffer("abc");//char[] value = new char["abc".length() + 16];

问题1. System.out.println(sb2.length());//这个length是外部添加内容的length,而不是value[]的length
问题2. 扩容问题:如果要添加的数据底层数组盛不下了,那就需要扩容底层的数组。
默认情况下,扩容为原来容量的2倍 + 2,同时将原有数组中的元素复制到新的数组中。
指导意义:开发中建议使用:StringBuffer(int capacity) 或 StringBuilder(int capacity)

@Test
public void test4(){
    StringBuffer sb1 = new StringBuffer("abc");
    sb1.setCharAt(0,'m');
    System.out.println(sb1);

    StringBuffer sb2 = new StringBuffer();
    System.out.println(sb2.length());//0
}

对比String、StringBuffer、StringBuilder三者的效率:
从高到低排列:StringBuilder > StringBuffer > String
String 效率如此低的原因是在不停的创建对象

    @Test
    public void test5(){
        //初始设置
        long startTime = 0L;
        long endTime = 0L;
        String text = "";
        StringBuffer buffer = new StringBuffer("");
        StringBuilder builder = new StringBuilder("");
        //开始对比
        startTime = System.currentTimeMillis();
        for (int i = 0; i < 9000; i++) {
            buffer.append(String.valueOf(i));
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuffer的执行时间:" + (endTime - startTime));

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 9000; i++) {
            builder.append(String.valueOf(i));
        }
        endTime = System.currentTimeMillis();
        System.out.println("StringBuilder的执行时间:" + (endTime - startTime));

        startTime = System.currentTimeMillis();
        for (int i = 0; i < 9000; i++) {
            text = text + i;
        }
        endTime = System.currentTimeMillis();
        System.out.println("String的执行时间:" + (endTime - startTime));
        
//        StringBuffer的执行时间:3
//        StringBuilder的执行时间:1
//        String的执行时间:174
    }

Calendar日历类(抽象类)的使用,注意在Calendar中,一月是0,以此类推... 十二月是11,周日是1,周一是2..,周六是9

    @Test
    public void testCalendar(){
        //1.实例化
        //方式一:创建其子类(GregorianCalendar)的对象
        //方式二:调用其静态方法getInstance()
        Calendar calendar = Calendar.getInstance();
    //    System.out.println(calendar.getClass());
    
        //2.常用方法
        //get()
        int days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
        System.out.println(calendar.get(Calendar.DAY_OF_YEAR));
    
        //set()
        //calendar可变性
        calendar.set(Calendar.DAY_OF_MONTH,22);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
    
        //add()
        calendar.add(Calendar.DAY_OF_MONTH,-3);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
    
        //getTime():日历类---> Date
        Date date = calendar.getTime();
        System.out.println(date);
    
        //setTime():Date ---> 日历类
        Date date1 = new Date();
        calendar.setTime(date1);
        days = calendar.get(Calendar.DAY_OF_MONTH);
        System.out.println(days);
    }

JDK8之前的日期时间API的问题
1 可变性:日期和时间这样的对象 一般要被设计为不可变的
2 偏移性:Date中的年份是从1900年开始的,月份从0开始
3 格式化: 格式化只对Date 有用,对Calendar这不行
4 此外他们也不是线程安全的,也不能处理闰秒等问题
JDK第一次引入时间是Date,第二次是Calendar,第三次引入是JDK8,它吸收了Joda-time的精华,这一次引入被认为是成功的引入。

    @Test
    public void testDate(){
        //偏移量
        Date date1 = new Date(2020 - 1900,9 - 1,8);
        System.out.println(date1);//Tue Sep 08 00:00:00 CST 2020
    }

    /*
        LocalDate、LocalTime、LocalDateTime 的使用
        说明:
        1.LocalDateTime相较于LocalDate、LocalTime,使用频率要高
        2.类似于Calendar
     */
    @Test
    public void test1(){
        //now():获取当前的日期、时间、日期+时间
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        LocalDateTime localDateTime = LocalDateTime.now();

        System.out.println(localDate); //2019-05-23
        System.out.println(localTime); //10:51:05.012
        System.out.println(localDateTime);//2019-05-23T10:51:05.012
        System.out.println("**********");

        //of():设置指定的年、月、日、时、分、秒。没有偏移量
        LocalDateTime localDateTime1 = LocalDateTime.of(2020, 10, 6, 13, 23, 43);
        System.out.println(localDateTime1);//2020-10-06T13:23:43


        //getXxx():获取相关的属性
        System.out.println(localDateTime.getDayOfMonth());//23
        System.out.println(localDateTime.getDayOfWeek());//THURSDAY
        System.out.println(localDateTime.getMonth());//MAY
        System.out.println(localDateTime.getMonthValue());//5
        System.out.println(localDateTime.getMinute());//51
        System.out.println("**********");

        //体现不可变性 跟像String对象一样
        //withXxx():设置相关的属性
        LocalDate localDate1 = localDate.withDayOfMonth(22);
        System.out.println(localDate);//2019-05-23
        System.out.println(localDate1);//2019-05-22


        LocalDateTime localDateTime2 = localDateTime.withHour(4);
        System.out.println(localDateTime);//2019-05-23T10:52:24.265
        System.out.println(localDateTime2);//2019-05-23T04:52:24.265
        System.out.println("--------------------");
        //不可变性
        LocalDateTime localDateTime3 = localDateTime.plusMonths(3);
        System.out.println(localDateTime);//2019-05-23T10:55:50.903
        System.out.println(localDateTime3);//2019-08-23T10:55:50.903

        LocalDateTime localDateTime4 = localDateTime.minusDays(6);
        System.out.println(localDateTime);//2019-05-23T10:55:50.903
        System.out.println(localDateTime4);//2019-05-17T10:55:50.903
    }

    /*
    Instant的使用 ,精度是纳秒级别
    类似于 java.util.Date类
     */
    @Test
    public void test2(){
        //now():获取本初子午线对应的标准时间
        Instant instant = Instant.now();
        System.out.println(instant);//2019-02-18T07:29:41.719Z

        //添加时间的偏移量 东八区,设置8
        OffsetDateTime offsetDateTime = instant.atOffset(ZoneOffset.ofHours(8));
        System.out.println(offsetDateTime);//2019-02-18T15:32:50.611+08:00

        //toEpochMilli():获取自1970年1月1日0时0分0秒(UTC)开始的毫秒数  ---> Date类的getTime()
        long milli = instant.toEpochMilli();
        System.out.println(milli);

        //ofEpochMilli():通过给定的毫秒数,获取Instant实例  -->Date(long millis)
        Instant instant1 = Instant.ofEpochMilli(1550475314878L);
        System.out.println(instant1);
    }

    /*
        DateTimeFormatter:格式化或解析日期、时间
        类似于SimpleDateFormat
     */

    @Test
    public void test3(){
//        方式一:预定义的标准格式。如:ISO_LOCAL_DATE_TIME;ISO_LOCAL_DATE;ISO_LOCAL_TIME
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
        //格式化:日期-->字符串
        LocalDateTime localDateTime = LocalDateTime.now();
        String str1 = formatter.format(localDateTime);
        System.out.println(localDateTime);//2019-05-23T11:05:56.612
        System.out.println(str1);//2019-05-23T11:05:56.612

        //解析:字符串 -->日期
        TemporalAccessor parse = formatter.parse("2019-02-18T15:42:18.797");
        System.out.println(parse);

//        方式二:
//        本地化相关的格式。如:ofLocalizedDateTime()
//        FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT :适用于LocalDateTime
        DateTimeFormatter formatter1 = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG);
        //格式化
        String str2 = formatter1.format(localDateTime);
        System.out.println(str2);//2019年2月18日 下午03时47分16秒


//      本地化相关的格式。如:ofLocalizedDate()
//      FormatStyle.FULL / FormatStyle.LONG / FormatStyle.MEDIUM / FormatStyle.SHORT : 适用于LocalDate
        DateTimeFormatter formatter2 = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
        //格式化
        String str3 = formatter2.format(LocalDate.now());
        System.out.println(str3);//2019-2-18


//       重点: 方式三:自定义的格式。如:ofPattern(“yyyy-MM-dd hh:mm:ss”)
        DateTimeFormatter formatter3 = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
        //格式化
        String str4 = formatter3.format(LocalDateTime.now());
        System.out.println(str4);//2019-02-18 03:52:09

        //解析
        TemporalAccessor accessor = formatter3.parse("2019-02-18 03:52:09");
        System.out.println(accessor);
    }

对象排序:Comparable接口与Comparator排序器

  • Comparable接口的方式一旦一定,保证Comparable接口实现类的对象在任何位置都可以比较大小。
  • Comparator接口属于临时性的比较。
    下面的Goods类实现了Comparable接口并且重写了compareTo()方法
    @Test
    public void test2(){
        Goods[] arr = new Goods[5];
        arr[0] = new Goods("lenovoMouse",34);
        arr[1] = new Goods("dellMouse",43);
        arr[2] = new Goods("xiaomiMouse",12);
        arr[3] = new Goods("huaweiMouse",65);
        arr[4] = new Goods("microsoftMouse",43);

        Arrays.sort(arr);

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

Comparator接口的使用:定制排序
1.背景:
当元素的类型没有实现java.lang.Comparable接口而又不方便修改代码,或者实了java.lang.Comparable接口的排序规则不适合当前的操作(比如接口里定义了按照名字排序,但是我当前场景下想按照年龄排序呢),那么可以考虑使用 Comparator 的对象来排序,接口排序和比较器排序更像主流与辅助的关系,我们再重写接口方法上定义一个对象的默认排序,但是有些时候我们需要用比较器临时用一下其他的排序规则。

    @Test
    public void test4(){
        Goods[] arr = new Goods[6];
        arr[0] = new Goods("lenovoMouse",34);
        arr[1] = new Goods("dellMouse",43);
        arr[2] = new Goods("xiaomiMouse",12);
        arr[3] = new Goods("huaweiMouse",65);
        arr[4] = new Goods("huaweiMouse",224);
        arr[5] = new Goods("microsoftMouse",43);

        Arrays.sort(arr, new Comparator() {
            //指明商品比较大小的方式:按照产品名称从低到高排序,再按照价格从高到低排序
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Goods && o2 instanceof Goods){
                    Goods g1 = (Goods)o1;
                    Goods g2 = (Goods)o2;
                    if(g1.getName().equals(g2.getName())){
                        return -Double.compare(g1.getPrice(),g2.getPrice());
                    }else{
                        return g1.getName().compareTo(g2.getName());
                    }
                }
                throw new RuntimeException("输入的数据类型不一致");
            }
        });

        System.out.println(Arrays.toString(arr));
    }
枚举

定义枚举

  • 方式一:jdk5.0之前,自定义枚举类
public class SeasonTest {

    public static void main(String[] args) {
        Season spring = Season.SPRING;
        System.out.println(spring);
    }
}
//自定义枚举类
class Season{
    //1.声明Season对象的属性:private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //2.私有化类的构造器,并给对象属性赋值
    private Season(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //3.提供当前枚举类的多个对象:public static final的
    public static final Season SPRING = new Season("春天","春暖花开");
    public static final Season SUMMER = new Season("夏天","夏日炎炎");
    public static final Season AUTUMN = new Season("秋天","秋高气爽");
    public static final Season WINTER = new Season("冬天","冰天雪地");

    //4.其他诉求1:获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
    //4.其他诉求1:提供toString()
    @Override
    public String toString() {
        return "Season{" +
                "seasonName='" + seasonName + '\'' +
                ", seasonDesc='" + seasonDesc + '\'' +
                '}';
    }
}
  • 方式二:jdk5.0,可以使用enum关键字定义枚举类
    使用enum关键字定义的枚举类实现接口的情况
    情况一:实现接口,在enum类中实现抽象方法
    情况二:让枚举类的对象分别实现接口中的抽象方法
interface Info{
    void show();
}

//使用enum关键字枚举类
enum Season1 implements Info{
    //1.提供当前枚举类的对象,多个对象之间用","隔开,末尾对象";"结束
    SPRING("春天","春暖花开"){
        @Override
        public void show() {
            //这里是没一个枚举对象的方法实现,实现差异化
            System.out.println("春天在哪里?");
        }
    },
    SUMMER("夏天","夏日炎炎"){
        @Override
        public void show() {
            System.out.println("宁夏");
        }
    },
    AUTUMN("秋天","秋高气爽"){
        @Override
        public void show() {
            System.out.println("秋天不回来");
        }
    },
    WINTER("冬天","冰天雪地"){
        @Override
        public void show() {
            System.out.println("大约在冬季");
        }
    };

    //2.声明Season对象的属性:private final修饰
    private final String seasonName;
    private final String seasonDesc;

    //2.私有化类的构造器,并给对象属性赋值

    private Season1(String seasonName,String seasonDesc){
        this.seasonName = seasonName;
        this.seasonDesc = seasonDesc;
    }

    //4.其他诉求1:获取枚举类对象的属性
    public String getSeasonName() {
        return seasonName;
    }

    public String getSeasonDesc() {
        return seasonDesc;
    }
//    //4.其他诉求1:提供toString()
//
//    @Override
//    public String toString() {
//        return "Season1{" +
//                "seasonName='" + seasonName + '\'' +
//                ", seasonDesc='" + seasonDesc + '\'' +
//                '}';
//    }

//    @Override
//    public void show() {
          //这个就是枚举的统一实现
//        System.out.println("这是一个季节");
//    }
}
public class SeasonTest1 {
    public static void main(String[] args) {
        Season1 summer = Season1.SUMMER;
        //toString():返回枚举类对象的名称
        System.out.println(summer.toString());

//        System.out.println(Season1.class.getSuperclass());
        System.out.println("****************");
        //values():返回所有的枚举类对象构成的数组
        Season1[] values = Season1.values();
        for(int i = 0;i < values.length;i++){
            System.out.println(values[i]);
            values[i].show();
        }
        System.out.println("****************");
        Thread.State[] values1 = Thread.State.values();
        for (int i = 0; i < values1.length; i++) {
            System.out.println(values1[i]);
        }

        //valueOf(String objName):返回枚举类中对象名是objName的对象。
        Season1 winter = Season1.valueOf("WINTER");
        //如果没有objName的枚举类对象,则抛异常:IllegalArgumentException
//        Season1 winter = Season1.valueOf("WINTER1");
        System.out.println(winter);
        winter.show();
    }
}
注解

注解其实就是代码里的特殊标记,这些标记信息可以在编译,类加载,运行的时候被读取出来,从而进行相应的处理,使用注解 程序员可以在不改变原有代码逻辑下 加入自己的逻辑。

/**
  * 3. 如何自定义注解:参照@SuppressWarnings定义
      * ① 注解声明为:@interface
      * ② 内部定义成员,通常使用value表示
      * ③ 可以指定成员的默认值,使用default定义
      * ④ 如果自定义注解没有成员,表明是一个标识作用。

     如果注解有成员,在使用注解时,需要指明成员的值。
     自定义注解必须配上注解的信息处理流程(使用反射)才有意义。
     自定义注解通过都会指明两个元注解:Retention、Target

     4. jdk 提供的4种元注解
       元注解:对现有的注解进行解释说明的注解
     Retention:指定所修饰的 Annotation 的生命周期:SOURCE\CLASS(默认行为)\RUNTIME
            只有声明为RUNTIME生命周期的注解,才能通过反射获取。
     Target:用于指定被修饰的 Annotation 能用于修饰哪些程序元素
     *******出现的频率较低*******
     Documented:表示所修饰的注解在被javadoc解析时,保留下来。
     Inherited:被它修饰的 Annotation 将具有继承性。

     6. jdk 8 中注解的新特性:可重复注解、类型注解

     6.1 可重复注解(定义):① 在MyAnnotation上声明@Repeatable,成员值为MyAnnotations.class

     6.2 类型注解:
     ElementType.TYPE_PARAMETER 表示该注解能写在类型变量的声明语句中(如:泛型声明)。
     ElementType.TYPE_USE 表示该注解能写在使用类型的任何语句中。

      *
 * @author shkstart
 * @create 2019 上午 11:37
 */
public class AnnotationTest {
    @Test
    public void testGetAnnotation(){
        Class<Student> studentClass = Student.class;
        Class clazz = Student.class;
        Annotation[] annotations = clazz.getAnnotations();
        for(int i = 0;i < annotations.length;i++){
            System.out.println(annotations[i]);
        }
    }
}


//jdk 8之前的写法:
//@MyAnnotations({@MyAnnotation(value="hi"),@MyAnnotation(value="hi")})
//jdk 8之后的写法:需要注解定义的时候加上@Repeatable元注解
@MyAnnotation(value="hi")
@MyAnnotation(value="abc")
class Person{
    private String name;
    private int age;

    public Person() {
    }
    @MyAnnotation
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @MyAnnotation
    public void walk(){
        System.out.println("人走路");
    }
    public void eat(){
        System.out.println("人吃饭");
    }
}

interface Info{
    void show();
}

class Student extends Person implements Info{

    @Override
    public void walk() {
        System.out.println("学生走路");
    }
    public void show() {

    }
}

class Generic<@MyAnnotation T>{

    public void show() throws @MyAnnotation RuntimeException{

        ArrayList<@MyAnnotation String> list = new ArrayList<>();

        int num = (@MyAnnotation int) 10L;
    }

}
@Inherited
@Repeatable(MyAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE,TYPE_PARAMETER,TYPE_USE})
public @interface MyAnnotation {
    String value() default "hello";
}
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
public @interface MyAnnotations {

    MyAnnotation[] value();
}

相关文章

网友评论

      本文标题:1 java常用类,枚举和注解

      本文链接:https://www.haomeiwen.com/subject/qmypzqtx.html