下面两种创建String对象的方式相同吗?
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s3 == s4); // false
}上述程序创建方式类似,为什么s1和s2引用的是同一个对象,而s3和s4不是呢? 在Java程序中,类似于:1, 2, 3,3.14,“hello”等字面类型的常量经常频繁使用,为了使程序的运行速度更快、更节省内存,Java为8种基本数据类型和String类都提供了常量池。 “池” 是编程中的一种常见的, 重要的提升效率的方式, 我们会在未来的学习中遇到各种 “内存池”, “线程池”, “数据库连接池” …
为了节省存储空间以及程序的运行效率,Java中引入了:
字符串常量池在JVM中是StringTable类,实际是一个固定大小的HashTable(一种高效用来进行查找的数据结构,后序给大家详细介绍),不同JDK版本下字符串常量池的位置以及默认大小是不同的:


当创建对象时,对象之间的关系大致如图所示 结论:只要是new的对象,都是唯一的。 通过上面例子可以看出:使用常量串创建String类型对象的效率更高,而且更节省空间。用户也可以将创建的字符串对象通过 intern 方式添加进字符串常量池中。
public static void main(String[] args) {
char[] chars= {'a','b','c'};
String s1 = new String(chars);
//s1.intern();
String s2 = "abc";
System.out.println(s1==s2);
}intern 是一个native方法(Native方法指:底层使用C++实现的,看不到其实现的源代码),该方法的作用是手动将创建的String对象添加到常量池中。
Java的反射(reflection)机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性,既然能拿到那么,我们就以修改部分类型信息;这种动态获取信息以及动态调用对象方法的功能称为java语言的反射(reflection)机制。
Java程序中许多对象在运行时会出现两种类型:运行时类型(RTTI)和编译时类型,例如Person p = newStudent();这句代码中p在编译时类型为Person,运行时类型为Student。程序需要在运行时发现对象和类的真实信息。而通过使用反射程序就能判断出该对象和类属于哪些类。



获得类中构造方法相关的方法:


在反射之前,我们需要做的第一步就是先拿到当前需要反射的类的Class对象,然后通过Class对象的核心方法,达到反射的目的,即:在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性,既然能拿到那么,我们就可以修改部分类型信息。
第一种,使用 Class.forName(“类的全路径名”); 静态方法。 前提:已明确类的全路径名。 第二种,使用 .class 方法。 说明:仅适合在编译前就已经明确要操作的 Class 第三种,使用类对象的 getClass() 方法
public static void main1(String[] args) throws ClassNotFoundException {
try{
Class<Student> c1 = Student.class;
System.out.println(c1);
Student s = new Student();
Class<? extends Student> c2 = s.getClass();
System.out.println(c2);
Class<?> c3 = null;
c3 = Class.forName("refelcetdemo.Student");
System.out.println(c3);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}注意过程中会涉及异常问题,需要解决一下。
public static void main(String[] args) {
try {
Class<?> c1 = Class.forName("refelcetdemo.Student");
Method method =
c1.getDeclaredMethod("function", String.class);
method.setAccessible(true);
Student student = (Student) c1.newInstance();
method.invoke(student,"调用成功");
}catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
public static void main4(String[] args) {
try {
Class<?> c1 = Class.forName("refelcetdemo.Student");
Field field = c1.getField("age");
field.setAccessible(true);
Student student = (Student) c1.newInstance();
field.set(student,9);
System.out.println(student);
}catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
public static void main3(String[] args) {
try {
Class<?> c1 = Class.forName("refelcetdemo.Student");
Constructor<Student> constructor =
(Constructor<Student>) c1.getDeclaredConstructor(String.class,int.class );
constructor.setAccessible(true);
Student student = constructor.newInstance("小明",6);
System.out.println(student);
}catch (ClassNotFoundException | NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public static void main2(String[] args) {
try{
Class<?> c1 = Class.forName("refelcetdemo.Student");
Student student = (Student) c1.newInstance();
System.out.println(c1);
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}这一部分是使用反射得到目标类,并且通过特定的方法分别得到目标类中的构造器,私有对象,私有方法。并且修改其中的变量的值。
优点:
缺点:
枚举是在JDK1.5以后引入的。主要用途是:将一组常量组织起来,在这之前表示一组常量通常使用定义常量的方式:
public static final int RED = 1;
public static final int GREEN = 2;
public static final int BLACK = 3;但是常量举例有不好的地方,例如:可能碰巧有个数字1,但是他有可能误会为是RED,现在我们可以直接用枚举来进行组织,这样一来,就拥有了类型,枚举类型。而不是普通的整形1.
public enum TestEnum {
RED,BLACK,GREEN;
}优点:将常量组织起来统一进行管理 场景:错误状态码,消息类型,颜色的划分,状态机等等… 本质:是 java.lang.Enum 的子类,也就是说,自己写的枚举类,就算没有显示的继承 Enum ,但是其默认继承了这个类。
switch语句
public enum TestEnum {
RED,BLACK,GREEN,WHITE;
public static void main(String[] args) {
TestEnum testEnum2 = TestEnum.BLACK;
switch (testEnum2) {
case RED:
System.out.println("red");
break;
case BLACK:
System.out.println("black");
break;
case WHITE:
System.out.println("WHITE");
break;
case GREEN:
System.out.println("black");
break;
default:
break;
}
}
}常用方法:

public static void main(String[] args) {
testEnum[] enums = testEnum.values();
for (testEnum anEnum : enums) {
System.out.println(anEnum.ordinal());
}
System.out.println(RED.compareTo(BLACK));
testEnum testEnum = enumdemo.testEnum.valueOf("heihei");
System.out.println(testEnum);
}补充知识: 1、当枚举对象有参数后,需要提供相应的构造函数 2、枚举的构造函数默认是私有的 这个一定要记住
RED("red",0),BLACK("black",1),GREEN("green",2),WHITE("white",3);
private String name;
private int key;
/**
* 1、当枚举对象有参数后,需要提供相应的构造函数
* 2、枚举的构造函数默认是私有的 这个一定要记住
* @param name
* @param key
*/
private testEnum (String name,int key) {
this.name = name;
this.key = key;
}优点:
缺点:
不能通过反射来获取枚举的构造。 原因是newInstance()函数中把枚举自动过滤了。

Lambda表达式是Java SE 8中一个重要的新特性。lambda表达式允许你通过表达式来代替功能接口。 lambda表达式就和方法一样,它提供了一个正常的参数列表和一个使用这些参数的主体(body,可以是一个表达式或一个代码块)。 Lambda 表达式(Lambda expression),基于数学中的λ演算得名,也可称为闭包(Closure) 。
基本语法: (parameters) -> expression 或 (parameters) ->{ statements; } Lambda表达式由三部分组成:
// 1. 不需要参数,返回值为 2
() -> 2
// 2. 接收一个参数(数字类型),返回其2倍的值
x -> 2 * x
// 3. 接受2个参数(数字),并返回他们的和
(x, y) -> x + y
// 4. 接收2个int型整数,返回他们的乘积
(int x, int y) -> x * y
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)
(String s) -> System.out.print(s)要了解Lambda表达式,首先需要了解什么是函数式接口,函数式接口定义:一个接口有且只有一个抽象方法 。 注意:

但是有这样一种特殊情况: JDK1.8新特性,default默认方法可以有具体的实现

特点:语法精简 1. 参数类型可以省略,如果需要省略,每个参数的类型都要省略。 2. 参数的小括号里面只有一个参数,那么小括号可以省略 3. 如果方法体当中只有一句代码,那么大括号可以省略 4. 如果方法体中只有一条语句,且是return语句,那么大括号可以省略,且去掉return关键字
public static void main2(String[] args) {
NoParameterReturn noParameterReturn = () -> 10;
System.out.println(noParameterReturn.test());
OneParameterReturn oneParameterReturn = a-> a;
System.out.println(oneParameterReturn.test(10));
MoreParameterReturn moreParameterReturn = (a,b) -> a+b;
System.out.println(moreParameterReturn.test(10,20));
}
public static void main1(String[] args) {
NoParameterNoReturn noParameterNoReturn = new NoParameterNoReturn(){
@Override
public void test(){
System.out.println("测试");
}
};
noParameterNoReturn.test();
NoParameterNoReturn noParameterNoReturn1 = ()->System.out.println("测试2");
noParameterNoReturn1.test();
OneParameterNoReturn oneParameterNoReturn = a-> System.out.println(a);
oneParameterNoReturn.test(10);
MoreParameterNoReturn moreParameterNoReturn = (a,b) -> System.out.println(a+b);
moreParameterNoReturn.test(1,2);
}public static void main3(String[] args) {
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
});
PriorityQueue<Integer> priorityQueue1 =
new PriorityQueue<>((o1,o2)->o1.compareTo(o2));
}public static void main(String[] args) {
int count = 10;
MoreParameterNoReturn moreParameterNoReturn = (int a,int b) -> {
System.out.println(count);
System.out.println(a+b);
};
//count = 99;
}在上述代码当中的变量count就是,捕获的变量。这个变量要么是被final修饰,如果不是被final修饰的 你要保证在使用之前,没有修改。
forEach() 方法演示 该方法在接口 Iterable 当中,原型如下:
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}该方法表示:对容器中的每个元素执行action指定的动作 。
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("bit");
list.add("hello");
list.add("lambda");
list.forEach(new Consumer<String>(){
@Override
public void accept(String str){
//简单遍历集合中的元素。
System.out.print(str+" ");
}
});
}输出结果:Hello bit hello lambda 我们可以修改为如下代码:
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("bit");
list.add("hello");
list.add("lambda");
list.forEach(str -> System.out.println(str+" "));
}sort()方法的演示 sort方法源码:该方法根据c指定的比较规则对容器元素进行排序。
public void sort(Comparator<? super E> c) {
final int expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, size, c);
if (modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
modCount++;
}public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("bit");
list.add("hello");
list.add("lambda");
list.sort(new Comparator<String>() {
@Override
public int compare(String str1, String str2){
//注意这里比较长度
return str1.length()-str2.length();
}
});
System.out.println(list);
}修改之后:
public static void main6(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("bit");
list.add("hello");
list.add("lambda");
list.sort(
(str1,str2)-> str1.length() - str2.length()
);
System.out.println(list);
}HashMap 的 forEach() 该方法原型如下:
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}作用是对Map中的每个映射执行action指定的操作。 代码示例:
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "bit");
map.put(3, "hello");
map.put(4, "lambda");
map.forEach(new BiConsumer<Integer, String>(){
@Override
public void accept(Integer k, String v){
System.out.println(k + "=" + v);
}
});
}输出结果: 1=hello 2=bit 3=hello 4=lambda 使用lambda表达式后的代码:
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "bit");
map.put(3, "hello");
map.put(4, "lambda");
map.forEach((k,v)-> System.out.println(k + "=" + v));
}Lambda表达式的优点很明显,在代码层次上来说,使代码变得非常的简洁。缺点也很明显,代码不易读。 优点:
缺点: