java怎么拦截某个对象
325
2022-12-12
Java9中对集合类扩展的of方法解析
目录java9 集合类扩展of方法Java9集合类中重载多个of方法原因有如下描述
Java9 集合类扩展of方法
package com.jd.collections;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Sethttp://;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamTest {
@Test
public void testSet() {
Set
System.out.println(integerSet);
}
@Test
public void testList() {
List
System.out.println(integerSet);
}
@Test
public void testMap() {
Map
System.out.println(stringMap);
Map.Entry
Map.Entry
Map.Entry
Map
System.out.println(mapOfEntries);
}
@Test
public void testStream1() {
Optional
System.out.println(integerOptional.get());
}
@Test
public void testStream2() {
Stream.of(1, 2, 3, 4, 5, 6).dropWhile(x -> x == 6)/*.takeWhile(x -> x == 2)*/.forEach(System.out::println);
}
@Test
public void testStream3() {
IntStream.of(1, 2, 3, 4, 5, 6).forEach(System.out::println);
}
@Test
public void testStream4() {
IntStream.iterate(1, i -> i < 10, i -> i + 2).forEach(System.out::println);
}
// @Test
// public void testFlow() {
// Flow.Processor
// }
}
Java9集合类中重载多个of方法原因
在java9 api的集合类中,有很多看似一样的重载of方法:
那这里有个问题是为什么有了VarArgs(可变长参数)方法,还需要定义那么多重载的方法呢?查看官方的更新日志中可以发现
有如下描述
http://openjdk.java.net/jeps/269
These will include varargs overloads, so that there is no fixed limit on the collection size. However, the collection instances so created may be tuned for smaller sizes. Special-case APIs (fixed-argument overloads) for up to ten of elements will be provided. While this introduces some clutter in the API, it avoids array allocation, initialization, and garbage collection overhead that is incurred by varargs calls. Significantly, the source code of the call site is the same regardless of whether a fixed-arg or varargs overload is called.
大致得意思是,虽然重载了这么多of方法会造成api的混乱,但它避免了varargs调用引起的数组分配,初始化和垃圾收集开销。因为固定参数的重载方法,返回的是一个immutable list(不可变集合)。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~