今天学习了Hashtable、Properties以及函数式接口记录一下
Hashtable我们可以拿来与HashMap与之比较,这样比较容易记忆。
线程不安全 | 线程安全 |
继承自java.util.AbstractMap<K, V> 父类 | 继承自java.util.Dictionary<K, V> 父类 |
并允许null值和null键 | 不允许任何键和值为null |
索引值:(n - 1) & hash | 索引值:(hash & 0x7FFFFFFF) % tab.length |
初始容量:默认16 | 初始容量:默认11 |
扩容:原来的2倍 | 扩容:原来的2倍+1 |
大多数情况下我们采用HashMap
Properties类是Hashtable的子类,它可以用来根据属性键获取属性值。Properties类提供了从属性文件中获取数据和将数据存储到属性文件中的方法。此外,它还可以用来获取系统的属性
Properties类表示一组持久的属性。Properties可以保存到流中或从流中加载。属性列表中的每个键及其对应的值都是一个字符串。
Proper一般用于SQL的配置。示例代码如下:
public class Class_17_Propreties {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.put("username", "12");
properties.put("password", "13");
//输入流
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("mysql.properties"));
System.out.println(properties.getProperty("username"));
System.out.println(properties.getProperty("password"));
//输出流
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("src/mysql2.properties"));
FileOutputStream writer = new FileOutputStream("src/mysql2.properties");
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(writer, "UTF-8");
properties.store(outputStream, "src/mysql.properties");
properties.store(outputStreamWriter, "华哥");
writer.flush();
writer.close();
// Properties prop = new Properties();
// prop.setProperty("name", "华哥");
// FileOutputStream fos = new FileOutputStream("src/test.properties");
// OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
// prop.store(osw, "123");
// osw.flush();
// osw.close();
}
}
输出结果如下:
Lammbda表达式
简化内部类的表达式。Lammbda表达式和函数式接口是组合起来用示例代码如下:
/*
*
* 习题三:
* 1)声明一个带两个泛型的函数式接口,发型类型为<T,R> T为参数,R为返回值
* 2)接口中声明对应抽象方法
* 3)在TestLambda类中声明方法,参数三个,两个long类型的参数,接口作为参数,接口实现中计算两个long型参数的和
* 4)再计算两个long型参数的乘积
* */
public class Hw_07 {
public static void main(String[] args) {
System.out.println(getResult(100L, 200L, (x, y) -> x + y));
}
public static long getResult(Long l1, Long l2, MyFunction<Long, Long> my) {
return my.getvalue(l1, l2);
}
}
@FunctionalInterface
interface MyFunction<T, R> {
public R getvalue(T t1, T t2);
}
输出结果如下:
函数式接口
函数式接口是Java8中引入的一个新概念。它是一种只有一个抽象方法的接口。它可以被隐式转换为lambda表达式或方法引用。函数式接口在Java8中引入,旨在支持Java中的函数式编程。Java提供了一个注解@FunctionalInterface,用于声明一个接口为函数式接口。如果一个接口被声明为函数式接口,但它包含多个抽象方法,则编译器会报错。函数式接口可以有任意数量的默认方法和静态方法。只要一个接口中只有一个抽象方法,它就是一个函数式接口。
四个常见的函数式接口:
Consumer:接受一个输入参数,无返回值。Function:接受一个输入参数,返回一个结果Predicate:接受一个输入参数,返回一个布尔值Supplier:无输入参数,返回一个结果。
今天总结了HashMap和Hashtable的区别。以及对函数接口有一个初步的认识。明天将继续加油!
文章为作者独立观点,不代表 股票程序化软件自动交易接口观点