我有一个包含字符串的列表,如下所示。
candidates = ["Hello", "World", "HelloWorld", "Foo", "bar", "ar"]
Run Code Online (Sandbox Code Playgroud)
我希望列表被过滤为["HelloWorld", "Foo", "Bar"],因为其他的是子字符串。我可以这样做,但不认为它很快或优雅。
def filter_not_substring(candidates):
survive = []
for a in candidates:
for b in candidates:
if a == b:
continue
if a in b:
break
else:
survive.append(a)
return survive
Run Code Online (Sandbox Code Playgroud)
有什么快速的方法可以做到吗?
Arrays.asList() 声明如下。
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
Run Code Online (Sandbox Code Playgroud)
因此,如您所知,要List使用数组初始化混凝土,您可以这样做:
@SafeVarargs
@SuppressWarnings("varargs")
public static <T> List<T> asList(T... a) {
return new ArrayList<>(a);
}
Run Code Online (Sandbox Code Playgroud)
但这又如何呢?
List<String> list = new ArrayList<>(new String[]{"hello", "world"});
Run Code Online (Sandbox Code Playgroud)
我预计它会起作用,但没有。
我明白为什么。这是因为ArrayList需求Collection类的构造函数之一。
那么,呢Arrays.asList()?
Varargs 被编译为数组,因此该方法可能会编译如下。
String[] strings = new String[] {"hello", "world"};
List<String> list = new ArrayList<>(Arrays.asList(strings));
Run Code Online (Sandbox Code Playgroud)
但它实际上返回ArrayList对象。为什么这是可能的?
这个问题可能会重复,所以请告诉我这是否属实。
我试图了解 Java 中的同步,但我不清楚“何时wait()在对象类中使用方法”。
假设我有如下简单的课程。
class Test {
static class Example {
int value = 0;
public synchronized void increment() {
value++;
}
}
public static void main(String[] args) throws InterruptedException {
Example example = new Example();
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(() -> example.increment());
threads[i].start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println(example.value);
}
}
Run Code Online (Sandbox Code Playgroud)
10 个线程尝试调用同步increment方法。这很有效,但奇怪的是我从未在方法notify()中调用方法increment() …