package tryAny.effectiveJava;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class OverloadTest {
public static String classify(Set<?> s) {
return "Set";
}
public static String classify(List<?> s) {
return "List";
}
public static String classify(Collection<?> s) {
return "Collection";
}
public static void main(String[] args) {
Collection<?>[] collections = { new HashSet<String>(), new ArrayList<String>(),
new HashMap<String, String>().values() };
for (Collection<?> c : collections) {
System.out.println(classify(c));
}
/**
* Collection <br>
* Collection <br>
* Collection
*/
}
}
package tryAny.effectiveJava;
import java.util.List;
public class OverrideTest {
public static void main(String[] args) {
List<Wine> l = List.of(new Wine(), new SparklingWine(), new Champagne());
for (Wine w : l) {
System.out.println(w.name());
/**
* wine<br>
* sparkling wine<br>
* champagne
*/
}
}
}
class Wine {
String name() {
return "wine";
}
}
class SparklingWine extends Wine {
@Override
String name() {
return "sparkling wine";
}
}
class Champagne extends SparklingWine {
@Override
String name() {
return "champagne";
}
}
package tryAny.effectiveJava;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
public class SetList {
public static void main(String[] args) {
Set<Integer> s = new TreeSet<>();
List<Integer> l = new ArrayList<>();
for (int i = -3; i < 3; i++) {
s.add(i);
l.add(i);
}
for (int i = 0; i < 3; i++) {
s.remove(i);
l.remove(i);
}
System.out.println(s + "" + l);// [-3, -2, -1] [-2, 0, 2]
}
}
exec.submit (System.out :: println); `` `. This submit method is overloaded with `` `submit (Runnable task);` `` and `` `submit (Callable <T> task);` `` so that the compiler cannot determine which to use. (** I don't understand why it's hard to judge. `` `System.out :: println
is an inexact method reference or something **). Anyway, to avoid confusion, you should avoid overloading with different functional interfaces at the same argument position.package tryAny.effectiveJava;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Snippet {
public static void main(String[] args) {
new Thread(System.out::println).start();
ExecutorService exec = Executors.newCachedThreadPool();
exec.submit(System.out::println); //Compile error
}
}
// Ensuring that 2 methods have identical behavior by forwarding
public boolean contentEquals(StringBuffer sb) {
return contentEquals((CharSequence) sb);
}
Recommended Posts