我正在将Java7代码移植到Java8,我想出了以下问题.在我的代码库中,我有两种方法:
public static <T> ImmutableSet<T> append(Set<T> set, T elem) {
return ImmutableSet.<T>builder().addAll(set).add(elem).build();
}
public static <T> ImmutableSet<T> append(Set<T> set, Set<T> elemSet) {
ImmutableSet.Builder<T> newSet = ImmutableSet.builder();
return newSet.addAll(set).addAll(elemSet).build();
Run Code Online (Sandbox Code Playgroud)
编译器在以下测试中返回有关方法附加的模糊匹配的错误:
@Test(expected = NullPointerException.class)
public void shouldAppendThrowNullPointerForNullSecondSet() {
ImmutableSet<Integer> obj = null;
CollectionUtils.append(ImmutableSet.of(1), obj);
}
Run Code Online (Sandbox Code Playgroud)
编译错误:
对append的引用是不明确的,CollectionUtils中的方法append(java.util.Set,T)和CollectionUtils中的方法append(java.util.Set,java.util.Set)匹配
如何重写这些函数以使用Java8引入的类型推断?
我想使用可变参数模板从结构中准备值对的列表.
#include <vector>
struct foo
{
foo(int a, int b)
: a(a), b(b) {}
int a;
int b;
};
struct Msg
{
std::vector<int> valueArray;
};
template<typename... Args>
Msg func(Args... args)
{
Msg msg;
msg.valueArray = { sizeof...(args), (args.a)..., (args.b)... };
return msg;
}
int main() {
Msg msg = func(foo{1,2}, foo{3,4}, foo{5,6});
}
Run Code Online (Sandbox Code Playgroud)
将返回func将返回的消息valueArray = [3, 1, 3, 5, 2, 4, 6].
有没有简单的方法来扩展可变参数的方式,valueArray会是什么样子valueArray = [3, 1, 2, 3, 4, 5, 6]?
我想在某个类中存储对变量的引用,并在此类中对其进行操作.操作应该修改原始变量.特别是下面的代码应该打印1而不是0.
class Test {
private Long metric;
public Test(Long m) {
this.metric = m;
++this.metric;
}
}
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Long metric = 0L;
Test test = new Test(metric);
System.out.println(metric);
}
}
Run Code Online (Sandbox Code Playgroud)
如何实现这种行为?