OnJava8-Examples/collections/AsListInference.java

39 lines
1.2 KiB
Java
Raw Permalink Normal View History

2015-12-15 11:47:04 -08:00
// collections/AsListInference.java
// (c)2021 MindView LLC: see Copyright.txt
2015-11-15 15:51:35 -08:00
// We make no guarantees that this code is fit for any purpose.
2016-09-23 13:23:35 -06:00
// Visit http://OnJava8.com for more book information.
2015-06-15 17:47:35 -07:00
import java.util.*;
class Snow {}
class Powder extends Snow {}
class Light extends Powder {}
class Heavy extends Powder {}
class Crusty extends Snow {}
class Slush extends Snow {}
public class AsListInference {
public static void main(String[] args) {
List<Snow> snow1 = Arrays.asList(
new Crusty(), new Slush(), new Powder());
2016-01-25 18:05:55 -08:00
//- snow1.add(new Heavy()); // Exception
//- snow1.remove(0); // Exception
2015-06-15 17:47:35 -07:00
2016-01-25 18:05:55 -08:00
List<Snow> snow2 = Arrays.asList(
new Light(), new Heavy());
//- snow2.add(new Slush()); // Exception
//- snow2.remove(0); // Exception
2015-06-15 17:47:35 -07:00
List<Snow> snow3 = new ArrayList<>();
2016-01-25 18:05:55 -08:00
Collections.addAll(snow3,
new Light(), new Heavy(), new Powder());
snow3.add(new Crusty());
snow3.remove(0);
2015-06-15 17:47:35 -07:00
2016-01-25 18:05:55 -08:00
// Hint with explicit type argument specification:
2015-06-15 17:47:35 -07:00
List<Snow> snow4 = Arrays.<Snow>asList(
2016-01-25 18:05:55 -08:00
new Light(), new Heavy(), new Slush());
//- snow4.add(new Powder()); // Exception
//- snow4.remove(0); // Exception
2015-06-15 17:47:35 -07:00
}
2015-09-07 11:44:36 -06:00
}