美文网首页
java面试题

java面试题

作者: 紫色红色黑色 | 来源:发表于2019-12-15 16:38 被阅读0次

重载和重写

引用深入理解Java中的重写和重载

重写的条件

参数列表必须完全与被重写方法的相同;
返回类型必须完全与被重写方法的返回类型相同;
访问级别的限制性一定不能比被重写方法的强;
访问级别的限制性可以比被重写方法的弱;
重写方法一定不能抛出新的检查异常或比被重写的方法声明的检查异常更广泛的检查异常
重写的方法能够抛出更少或更有限的异常(也就是说,被重写的方法声明了异常,但重写的方法可以什么也不声明)
不能重写被标示为final的方法;
如果不能继承一个方法,则不能重写这个方法。

重载的条件

被重载的方法必须改变参数列表;
被重载的方法可以改变返回类型;
被重载的方法可以改变访问修饰符;
被重载的方法可以声明新的或更广的检查异常;
方法能够在同一个类中或者在一个子类中被重载。

return和finally

引用try-catch-finally语句中return的执行顺序思考
1.如果finally中有return语句,则会将try中的return语句“覆盖”掉,直接执行finally中的return语句,得到返回值,这样便无法得到try之前保留好的返回值。
2如果finally中没有return语句,也没有改变要返回值,则执行完finally中的语句后,会接着执行try中的return语句,返回之前保留的值。
3如果finally中没有return语句,但是改变了要返回的值,这里有点类似与引用传递和值传递的区别,分以下两种情况:

  • 如果return的数据是基本数据类型或文本字符串,则在finally中对该基本数据的改变不起作用,try中的return语句依然会返回进入finally块之前保留的值。
  • 如果return的数据是引用数据类型,而在finally中对该引用数据类型的属性值的改变起作用,try中的return语句返回的就是在finally中改变后的该属性的值。
    @Test
    public void testRuturnAndFinally() {
        //false
        System.out.println($returnAndFinallyBoolean1());
        //true
        System.out.println($returnAndFinallyBoolean2());
        //Student(name=lilly)
        System.out.println($returnAndFinallyObject());
    }

    private static boolean $returnAndFinallyBoolean1() {
        boolean flag = false;
        try {
            return flag;
        } finally {
            flag = true;
        }
    }

    private static boolean $returnAndFinallyBoolean2() {
        boolean flag = false;
        try {
            return flag;
        } finally {
            flag = true;
            return flag;
        }
    }

    private static Student $returnAndFinallyObject() {
        Student student = new Student();

        try {
            student.setName("lucy");
            return student;
        } finally {
            student.setName("lilly");
        }
    }

null

下面代码可以正常运行。
1.null可以转换为java中所有类型。转换后还是null。
2.静态方法调用和类名绑定,和对象无关。

public class NULL {

    public static void haha() {
        System.out.println("haha");
    }

    public static void main(String[] args) {
        ((NULL)null).haha();
    }
}

Throwable

java的顶级异常类。实现Serializable接口。有子类Exception和Error。
Error是系统级缺陷或异常,程序无法修复。Exception是程序有缺陷导致,可以修复的。

Comparable和Comparator

实现Comparable,重写compareTo(),表示类具有比较的能力。Comparator是一个比较器,以何种算法比较。


@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Student1 implements Comparable<Student1> {

    private int age;

    @Override
    public int compareTo(Student1 o) {
        return age - o.age;
    }
}
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Student2 {

    private int age;

}
public static void main(String[] args) {

    TreeSet<Student1> student1s = Sets.newTreeSet();
    student1s.add(new Student1(10));
    student1s.add(new Student1(13));
    student1s.add(new Student1(14));

    // [Student1(age=10), Student1(age=13), Student1(age=14)]
    System.out.println(student1s);

    List<Student2> student2s = Lists.newArrayList(new Student2(10), new Student2(12), new Student2(9));

    Collections.sort(student2s, new Comparator<Student2>() {
        @Override
        public int compare(Student2 o1, Student2 o2) {
            return o1.getAge() - o2.getAge();
        }
    });

    // [Student2(age=9), Student2(age=10), Student2(age=12)]
    System.out.println(student2s);

}

HashSet和TreeSet

都是Set,不允许元素重复。
HashSet是哈希表实现,使用hashCode()和equals()确定元素是否重复,可以且只能存入一个null值。
TreeSet是红黑树实现,元素是有序的且需要实现Comparable接口,使用compareTo()比较元素。不可以存入null。

IO

BIO读取写入文件

public static void main(String[] args) {
    File file = new File("/Users/lucy/Desktop/bio.txt");
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(file);
        out.write("hello,lucy\n".getBytes(UTF_8));
        out.write("my name is lilei\n".getBytes(UTF_8));
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    FileInputStream in = null;
    try {
        in = new FileInputStream(file);
        int len = 0;
        byte[] bytes = new byte[12];
        while ((len = in.read(bytes)) != -1) {
            System.out.print(new String(bytes, 0, len, UTF_8));
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

NIO读取写入文件

public static void main(String[] args) {
    File file = new File("/Users/lucy/Desktop/bio.txt");

    FileInputStream in = null;
    try {
        in = new FileInputStream(file);
        FileChannel inChannel = in.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(3);

        int len = -1;

        while ((len = inChannel.read(byteBuffer)) != -1) {
            byteBuffer.clear();
            System.out.print(new String(byteBuffer.array(), 0, len, UTF_8));
        }
        inChannel.close();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    FileOutputStream out = null;
    try {
        // append=true追加写
        out = new FileOutputStream(file, true);
        FileChannel outChannel = out.getChannel();

        String hello = "aio write:nice to meet you" + System.getProperty("line.separator");
        ByteBuffer byteBuffer = UTF_8.encode(hello);

        int len = 0;
        while ((len = outChannel.write(byteBuffer)) != 0) {
            System.out.println("写入长度:" + len);
        }
        outChannel.close();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

AIO读取写入文件

public class AIOReadDemo {

    public static void main(String[] args) {
        Path path = Paths.get("/Users/lucy/Desktop/bio.txt");

        // completionHandler
        try {
            AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            asynchronousFileChannel.read(byteBuffer, 0, "hello,world", new CompletionHandler<Integer, String>() {
                @Override
                public void completed(Integer result, String attachment) {
                    System.out.print(new String(byteBuffer.array()));
                }

                @Override
                public void failed(Throwable exc, String attachment) {
                    exc.printStackTrace();
                    try {
                        asynchronousFileChannel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            
            asynchronousFileChannel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }


        System.out.println("future 回调");

        // future
        try {
            AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path);
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            Future<Integer> future = asynchronousFileChannel.read(byteBuffer, 0);
            Integer result = future.get();

            byteBuffer.flip();

            String s = new String(byteBuffer.array(), 0, byteBuffer.limit(), UTF_8);

            System.out.print(s);

            asynchronousFileChannel.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


    }
}
public class AIOWriteDemo {

    public static void main(String[] args) {

        Path path = Paths.get("/Users/lucy/Desktop/aio.txt");

        try {
            AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            String hello = "aio:catch you later" + System.getProperty("line.separator");
            byteBuffer.put(hello.getBytes(UTF_8));
            byteBuffer.flip();

            asynchronousFileChannel.write(byteBuffer, 0, "hello,world", new CompletionHandler<Integer, String>() {
                @Override
                public void completed(Integer result, String attachment) {

                }

                @Override
                public void failed(Throwable exc, String attachment) {
                    try {
                        asynchronousFileChannel.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            asynchronousFileChannel.close();

        } catch (IOException e) {
            e.printStackTrace();
        }




        try {
            AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.WRITE);

            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            String hello = "aio:catch you later" + System.getProperty("line.separator");
            byteBuffer.put(hello.getBytes(UTF_8));
            byteBuffer.flip();

            Future<Integer> future = asynchronousFileChannel.write(byteBuffer, 0);

            Integer result = future.get();

            System.getProperty("write:" + result);

            asynchronousFileChannel.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }
}

AIO问题

aio在apend文件时,总是报错没有append权限。

创建对象方式

1.new:调用构造器创建
2.反射:newInstance(),这样也是调用构造器
3.clone:不调用构造器。实现Cloneable接口,重写Object的clone()

public class User implements Cloneable {

    public User() {
        System.out.println("NoArgsConstructor");
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}
public static void main(String[] args) {

    User user = new User();

    try {
        // 不调用构造器
        User user3 = (User) user.clone();
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }

    try {
        User user1 = User.class.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        e.printStackTrace();
    }

    try {
        Constructor<User> constructor = User.class.getConstructor();
        User user2 = constructor.newInstance();
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
        e.printStackTrace();
    }

}

相关文章

网友评论

      本文标题:java面试题

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