Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
The emergence of support of functions and lambda expressions as first-class citizens in Java 8 gives us a tremendous opportunity to adapt the concepts of functional programming to the Java language.
Concurrent Programming in Java provides a brief overview of the following topics:
• Java language support for concurrency
• Concurrency utilities (java.util.concurrent package)
• Java collections for multithreading (java.util package)
• Parallel streams in Java 8.
Try out the examples. Source code here: https://github.com/CodeOpsTech/ConcurrentJava
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
Slides for a lightning talk on Java 8 lambda expressions I gave at the Near Infinity (www.nearinfinity.com) 2013 spring conference.
The associated sample code is on GitHub at https://github.com/sleberknight/java8-lambda-samples
This presentation provides an overview of key topics in Java class design; also covers best practices/tips and quiz questions. Based on our OCP 8 book.
This presentation is on advanced debugging using Java bytecodes (presented in Core Java meetup on 1st October in Accion Labs). If you are a Java developer and are interested in knowing advanced debugging techniques or understanding bytecodes, this presentation is for you.
In Java 8, the java.util.function has numerous built-in interfaces. Other packages in the Java library (notably java.util.stream package) make use of the interfaces defined in this package. Java 8 developers should be familiar with using key interfaces provided in this package. This presentation provides an overview of four key functional interfaces (Consumer, Supplier, Function, and Predicate) provided in this package.
The emergence of support of functions and lambda expressions as first-class citizens in Java 8 gives us a tremendous opportunity to adapt the concepts of functional programming to the Java language.
Concurrent Programming in Java provides a brief overview of the following topics:
• Java language support for concurrency
• Concurrency utilities (java.util.concurrent package)
• Java collections for multithreading (java.util package)
• Parallel streams in Java 8.
Try out the examples. Source code here: https://github.com/CodeOpsTech/ConcurrentJava
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
This presentation takes a case-study based approach to design patterns. A purposefully simplified example of expression trees is used to explain how different design patterns can be used in practice. Examples are in C#, but is relevant for anyone who is from object oriented background.
Java programming presentations By Daroko blog
Do not just read java as a programmer, find projects and start making some Money, at DAROKO BLOG,WE Guide you through what you have learned in the classroom to a real business Environment, find java applications to a real business Environment, find also all IT Solutions and How you can apply them, find the best companies where you can get the IT jobs worldwide, Find java contract, Complete and start making some cash, find clients within your Country, refer and get paid when you complete the work.
Not Just a contact, at daroko Blog(www.professionalbloggertricks.com/),you are also being taught How you can apply all IT related field in real world.
Simply Google, Daroko Blog or visit (www.professionalbloggertricks.com/) to Know More about all these service now.
Do not just learn and god, Apply them in real world
Using a circularly-linked list made the solution trivial. The solution would have been more difficult if an array had been used. This illustrates the fact that the choice of the appropriate data structures can significantly simplify an algorithm. It can make the algorithm much faster and efficient.
Labprogram.java
LinkedList.java
import java.util.NoSuchElementException;
public class LinkedList {
private class Node {
private T data;
private Node next;
private Node prev;
public Node(T data) {
this.data = data;
this.next = null;
this.prev = null;
}
}
private int length;
private Node first;
private Node last;
private Node iterator;
/**** CONSTRUCTORS ****/
public LinkedList() {
first = null;
last = null;
iterator = null;
length = 0;
}
/**
* Converts the given array into a LinkedList
*
* @param array the array of values to insert into this LinkedList
* @postcondition
*/
public LinkedList(T[] array) {
}
/**
* Instantiates a new LinkedList by copying another List
*
* @param original the LinkedList to copy
* @postcondition a new List object, which is an identical,
* but separate, copy of the LinkedList original
*/
public LinkedList(LinkedList original) {
}
public T getFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return first.data;
}
public T getLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
return last.data;
}
public T getIterator() throws NullPointerException {
if (iterator != null) {
return iterator.data;
} else {
throw new NullPointerException("Iterator is off the end opf the list.");
}
}
public int getLength() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean offEnd() {
return iterator == null;
}
public void addFirst(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
newNode.next = first;
first.prev = newNode;
first = newNode;
}
length++;
}
public void addLast(T data) {
Node newNode = new Node(data);
if (isEmpty()) {
first = newNode;
last = newNode;
} else {
last.next = newNode;
newNode.prev = last;
last = newNode;
}
length++;
}
public void addIterator(T data) throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("addIterator Iterator is off end.");
}
if (iterator == last) {
addLast(data);
} else {
Node newNode = new Node(data);
Node next = iterator.next;
newNode.next = next;
newNode.prev = iterator;
iterator.next = newNode;
next.prev = newNode;
length++;
}
}
public void removeFirst() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == first) {
iterator = null;
}
first = first.next;
first.prev = null;
}
length--;
}
public void removeLast() throws NoSuchElementException {
if (isEmpty()) {
throw new NoSuchElementException("The list is empty");
}
if (length == 1) {
first = null;
last = null;
iterator = null;
} else {
if (iterator == last) {
iterator = null;
}
last = last.prev;
last.next = null;
}
length--;
}
public void removeIterator() throws NullPointerException {
if (offEnd()) {
throw new NullPointerException("Iterator is off the end opf the list.");
}
if (iterator .
A brief overview about how to write human readable and meaningful code. Here is described why and how to write meaningful names of variables or method, what to follow about writing a function for SRP / Open-Closed principle rule, when to write comments and rules of Code Formatting. Advantages of clean code is also described here.
JavaOne 2016 - Learn Lambda and functional programmingHenri Tremblay
This tutorial walks through tons of examples. You will learn everything you need to know about lambdas and functional programming in Java 8. I'm the supplier. You’re the consumer (and you will get the joke after the session).
On March 2014, Java 8 was released. These informal slides describe the new elements of the programming languages, focusing on those taken from the functional paradigm.
Software Engineering, Software Consulting, Tech Lead.
Spring Boot, Spring Cloud, Spring Core, Spring JDBC, Spring Security,
Spring Transaction, Spring MVC,
Log4j, REST/SOAP WEB-SERVICES.
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar
The European Union Agency for Law Enforcement Cooperation (Europol) has suffered an alleged data breach after a notorious threat actor claimed to have exfiltrated data from its systems. Infamous data leaker IntelBroker posted on the even more infamous BreachForums hacking forum, saying that Europol suffered a data breach this month.
The alleged breach affected Europol agencies CCSE, EC3, Europol Platform for Experts, Law Enforcement Forum, and SIRIUS. Infiltration of these entities can disrupt ongoing investigations and compromise sensitive intelligence shared among international law enforcement agencies.
However, this is neither the first nor the last activity of IntekBroker. We have compiled for you what happened in the last few days. To track such hacker activities on dark web sources like hacker forums, private Telegram channels, and other hidden platforms where cyber threats often originate, you can check SOCRadar’s Dark Web News.
Stay Informed on Threat Actors’ Activity on the Dark Web with SOCRadar!
Into the Box Keynote Day 2: Unveiling amazing updates and announcements for modern CFML developers! Get ready for exciting releases and updates on Ortus tools and products. Stay tuned for cutting-edge innovations designed to boost your productivity.
How Recreation Management Software Can Streamline Your Operations.pptxwottaspaceseo
Recreation management software streamlines operations by automating key tasks such as scheduling, registration, and payment processing, reducing manual workload and errors. It provides centralized management of facilities, classes, and events, ensuring efficient resource allocation and facility usage. The software offers user-friendly online portals for easy access to bookings and program information, enhancing customer experience. Real-time reporting and data analytics deliver insights into attendance and preferences, aiding in strategic decision-making. Additionally, effective communication tools keep participants and staff informed with timely updates. Overall, recreation management software enhances efficiency, improves service delivery, and boosts customer satisfaction.
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Shahin Sheidaei
Games are powerful teaching tools, fostering hands-on engagement and fun. But they require careful consideration to succeed. Join me to explore factors in running and selecting games, ensuring they serve as effective teaching tools. Learn to maintain focus on learning objectives while playing, and how to measure the ROI of gaming in education. Discover strategies for pitching gaming to leadership. This session offers insights, tips, and examples for coaches, team leads, and enterprise leaders seeking to teach from simple to complex concepts.
How to Position Your Globus Data Portal for Success Ten Good PracticesGlobus
Science gateways allow science and engineering communities to access shared data, software, computing services, and instruments. Science gateways have gained a lot of traction in the last twenty years, as evidenced by projects such as the Science Gateways Community Institute (SGCI) and the Center of Excellence on Science Gateways (SGX3) in the US, The Australian Research Data Commons (ARDC) and its platforms in Australia, and the projects around Virtual Research Environments in Europe. A few mature frameworks have evolved with their different strengths and foci and have been taken up by a larger community such as the Globus Data Portal, Hubzero, Tapis, and Galaxy. However, even when gateways are built on successful frameworks, they continue to face the challenges of ongoing maintenance costs and how to meet the ever-expanding needs of the community they serve with enhanced features. It is not uncommon that gateways with compelling use cases are nonetheless unable to get past the prototype phase and become a full production service, or if they do, they don't survive more than a couple of years. While there is no guaranteed pathway to success, it seems likely that for any gateway there is a need for a strong community and/or solid funding streams to create and sustain its success. With over twenty years of examples to draw from, this presentation goes into detail for ten factors common to successful and enduring gateways that effectively serve as best practices for any new or developing gateway.
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus
As part of the DOE Integrated Research Infrastructure (IRI) program, NERSC at Lawrence Berkeley National Lab and ALCF at Argonne National Lab are working closely with General Atomics on accelerating the computing requirements of the DIII-D experiment. As part of the work the team is investigating ways to speedup the time to solution for many different parts of the DIII-D workflow including how they run jobs on HPC systems. One of these routes is looking at Globus Compute as a way to replace the current method for managing tasks and we describe a brief proof of concept showing how Globus Compute could help to schedule jobs and be a tool to connect compute at different facilities.
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Anthony Dahanne
Les Buildpacks existent depuis plus de 10 ans ! D’abord, ils étaient utilisés pour détecter et construire une application avant de la déployer sur certains PaaS. Ensuite, nous avons pu créer des images Docker (OCI) avec leur dernière génération, les Cloud Native Buildpacks (CNCF en incubation). Sont-ils une bonne alternative au Dockerfile ? Que sont les buildpacks Paketo ? Quelles communautés les soutiennent et comment ?
Venez le découvrir lors de cette session ignite
top nidhi software solution freedownloadvrstrong314
This presentation emphasizes the importance of data security and legal compliance for Nidhi companies in India. It highlights how online Nidhi software solutions, like Vector Nidhi Software, offer advanced features tailored to these needs. Key aspects include encryption, access controls, and audit trails to ensure data security. The software complies with regulatory guidelines from the MCA and RBI and adheres to Nidhi Rules, 2014. With customizable, user-friendly interfaces and real-time features, these Nidhi software solutions enhance efficiency, support growth, and provide exceptional member services. The presentation concludes with contact information for further inquiries.
Why React Native as a Strategic Advantage for Startup Innovation.pdfayushiqss
Do you know that React Native is being increasingly adopted by startups as well as big companies in the mobile app development industry? Big names like Facebook, Instagram, and Pinterest have already integrated this robust open-source framework.
In fact, according to a report by Statista, the number of React Native developers has been steadily increasing over the years, reaching an estimated 1.9 million by the end of 2024. This means that the demand for this framework in the job market has been growing making it a valuable skill.
But what makes React Native so popular for mobile application development? It offers excellent cross-platform capabilities among other benefits. This way, with React Native, developers can write code once and run it on both iOS and Android devices thus saving time and resources leading to shorter development cycles hence faster time-to-market for your app.
Let’s take the example of a startup, which wanted to release their app on both iOS and Android at once. Through the use of React Native they managed to create an app and bring it into the market within a very short period. This helped them gain an advantage over their competitors because they had access to a large user base who were able to generate revenue quickly for them.
Strategies for Successful Data Migration Tools.pptxvarshanayak241
Data migration is a complex but essential task for organizations aiming to modernize their IT infrastructure and leverage new technologies. By understanding common challenges and implementing these strategies, businesses can achieve a successful migration with minimal disruption. Data Migration Tool like Ask On Data play a pivotal role in this journey, offering features that streamline the process, ensure data integrity, and maintain security. With the right approach and tools, organizations can turn the challenge of data migration into an opportunity for growth and innovation.
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Designing for Privacy in Amazon Web ServicesKrzysztofKkol1
Data privacy is one of the most critical issues that businesses face. This presentation shares insights on the principles and best practices for ensuring the resilience and security of your workload.
Drawing on a real-life project from the HR industry, the various challenges will be demonstrated: data protection, self-healing, business continuity, security, and transparency of data processing. This systematized approach allowed to create a secure AWS cloud infrastructure that not only met strict compliance rules but also exceeded the client's expectations.
Advanced Flow Concepts Every Developer Should KnowPeter Caitens
Tim Combridge from Sensible Giraffe and Salesforce Ben presents some important tips that all developers should know when dealing with Flows in Salesforce.
Developing Distributed High-performance Computing Capabilities of an Open Sci...Globus
COVID-19 had an unprecedented impact on scientific collaboration. The pandemic and its broad response from the scientific community has forged new relationships among public health practitioners, mathematical modelers, and scientific computing specialists, while revealing critical gaps in exploiting advanced computing systems to support urgent decision making. Informed by our team’s work in applying high-performance computing in support of public health decision makers during the COVID-19 pandemic, we present how Globus technologies are enabling the development of an open science platform for robust epidemic analysis, with the goal of collaborative, secure, distributed, on-demand, and fast time-to-solution analyses to support public health.
Enhancing Research Orchestration Capabilities at ORNL.pdfGlobus
Cross-facility research orchestration comes with ever-changing constraints regarding the availability and suitability of various compute and data resources. In short, a flexible data and processing fabric is needed to enable the dynamic redirection of data and compute tasks throughout the lifecycle of an experiment. In this talk, we illustrate how we easily leveraged Globus services to instrument the ACE research testbed at the Oak Ridge Leadership Computing Facility with flexible data and task orchestration capabilities.
In software engineering, the right architecture is essential for robust, scalable platforms. Wix has undergone a pivotal shift from event sourcing to a CRUD-based model for its microservices. This talk will chart the course of this pivotal journey.
Event sourcing, which records state changes as immutable events, provided robust auditing and "time travel" debugging for Wix Stores' microservices. Despite its benefits, the complexity it introduced in state management slowed development. Wix responded by adopting a simpler, unified CRUD model. This talk will explore the challenges of event sourcing and the advantages of Wix's new "CRUD on steroids" approach, which streamlines API integration and domain event management while preserving data integrity and system resilience.
Participants will gain valuable insights into Wix's strategies for ensuring atomicity in database updates and event production, as well as caching, materialization, and performance optimization techniques within a distributed system.
Join us to discover how Wix has mastered the art of balancing simplicity and extensibility, and learn how the re-adoption of the modest CRUD has turbocharged their development velocity, resilience, and scalability in a high-growth environment.
Experience our free, in-depth three-part Tendenci Platform Corporate Membership Management workshop series! In Session 1 on May 14th, 2024, we began with an Introduction and Setup, mastering the configuration of your Corporate Membership Module settings to establish membership types, applications, and more. Then, on May 16th, 2024, in Session 2, we focused on binding individual members to a Corporate Membership and Corporate Reps, teaching you how to add individual members and assign Corporate Representatives to manage dues, renewals, and associated members. Finally, on May 28th, 2024, in Session 3, we covered questions and concerns, addressing any queries or issues you may have.
For more Tendenci AMS events, check out www.tendenci.com/events
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...informapgpstrackings
Keep tabs on your field staff effortlessly with Informap Technology Centre LLC. Real-time tracking, task assignment, and smart features for efficient management. Request a live demo today!
For more details, visit us : https://informapuae.com/field-staff-tracking/
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Java Generics for Dummies
1. Generics for Dummies
...or how to shoot an elephant
from five feet, and miss!
Knut Mork – 22.2.2005
2. "The increase in complexity is increasing,
in part because of the natural, inevitable trend of technology
to put together ever-more powerful solutions
to problems we never realized we had.”
Donald Norman
3. Traditional example
List myIntList = new ArrayList();
myIntList.add(new Integer(0));
Integer x = (Integer) myIntList.iterator().next();
Same example using generics
List<Integer> myIntList = new ArrayList<Integer>();
myIntList.add(new Integer(0));
Integer x = myIntList.iterator().next();
4. Excerpt from java.util:
public interface List<E> {
void add(E x);
Iterator<E> iterator();
}
public interface Iterator<E> {
E next();
boolean hasNext();
}
5. • What ?
– To abstract over types
• Why ?
– Safer code, eliminate run-time checks
– Strong typing (not loose info)
– Remove (visible) down-casting
– Reduce awful, but necessary javadoc comments
– Increase the indend of your code/interface
– Others ?
• Where ?
– Collections, reflection (but problems with impl), others ?
• When ?
– Introduced in Java 1.5
6. No more casting ?
Basket<Fruit> basket = new Basket<Fruit>();
basket.addElement(new Apple());
Apple apple = (Apple) basket.pickElement();
8. “Any fool can write code that a computer can understand.
Good programmers write code that humans can understand.”
Martin Fowler
9. Real example from java.util.Collections:
public static <T extends Object &
Comparable<? super T>> max(Collection<? extends T> coll)
public static Object max(Collection coll) JDK 1.5
JDK 1.4
10. Example - subtyping
List<String> ls = new ArrayList<String>();
List<Object> lo = ls;
lo.add(new Object());
String s = ls.get(0);
11. Example - subtyping
List<String> ls = new ArrayList<String>();
List<Object> lo = ls; // compile-time error
lo.add(new Object());
String s = ls.get(0);
12. Traditional example2
void printCollection(Collection c) {
Iterator i = c.iterator();
for(k = 0; k < c.size(); k++) {
System.out.println(i.next());
}
}
Same example2 using generics
void printCollection(Collection<Object> c) {
for(Object e : c) {
System.out.println(e);
}
}
13. Traditional example2
void printCollection(Collection c) {
Iterator i = c.iterator();
for(k = 0; k < c.size(); k++) {
System.out.println(i.next());
}
}
Same example2 using generics
void printCollection(Collection<?> c) {
for(Object e : c) {
System.out.println(e);
}
}
14. But, on the other hand...
Collection<?> c = new ArrayList<String>();
c.add(new Object()); // compile-time error
15. It gets worse...
”The single biggest enemy of reliability
(and perhaps software quality in general)
is complexity.”
Bertrand Meyer
16. Bounded Wildcards
public void eatAll (List<Fruit> fruites) {
for (Fruit f: fruites) {
f.eat(this);
}
}
public void eatAll(List<? extends Fruit> fruites) {
...
}
17. Bounded Wildcards
public void addBanana(List<? extends Fruit> fruites) {
fruites.add(0, new Banana());
}
18. Bounded Wildcards
public void addBanana(List<? extends Fruit> fruites) {
fruites.add(0, new Banana()); // compile-time error
}
19. ...a lot worse...
"Once a satisfactory product has been achieved,
further change may be counterproductive,
especially if the product is successful.
You have to know when to stop.”
Donald Norman
20. Example 3
static void fromArrayToCollection(Object[] a, Collection c) {
for (Object o : a) {
c.add(o);
}
}
21. Example 3
static void fromArrayToCollection(Object[] a, Collection c) {
for (Object o : a) {
c.add(o);
}
}
Generic version:
static void fromArrayToCollection(Object[] a, Collection<?> c) {
for (Object o : a) {
c.add(o);
}
}
22. Example 3
static void fromArrayToCollection(Object[] a, Collection c) {
for (Object o : a) {
c.add(o);
}
}
Generic version:
static void fromArrayToCollection(Object[] a, Collection<?> c) {
for (Object o : a) {
c.add(o); // compile-time error
}
}
23. Example 3
static void fromArrayToCollection(Object[] a, Collection c) {
for (Object o : a) {
c.add(o);
}
}
Generic working version:
static <T> void fromArrayToCollection(T[] a, Collection<T> c) {
for (T o : a) {
c.add(o);
}
}
24. ”Under the hood”
”When simple things need instruction,
it is a certain sign of poor design.”
Donald Norman
25. Traditional example
List myIntList = new ArrayList();
myIntList.add(new Integer(0));
Integer x = (Integer) myIntList.iterator().next();
Same example using generics
List<Integer> myIntList = new ArrayList<Integer>();
myIntList.add(new Integer(0));
Integer x = myIntList.iterator().next();
26. List <String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
System.out.println(l1.getClass() == l2.getClass());
Output result ?
27. Collection cs = new ArrayList<String>();
if(cs instanceof Collection<String>) {...}
Output result ?
29. Using legacy code in 1.5
List fruitList1 = new ArrayList<Fruit>();
fruitList1.add(new Apple()); // warning
List fruitList2 = new ArrayList();
fruitList2 = juggle(fruitList2); // warning
List<Fruit> fruitList3 = new ArrayList<Fruit>();
fruitList3 = eat(fruitList3); // warning
public List eat(List fruits) {...}
public List<Fruit> juggle(List<Fruit> fruits) {...}
30. Using legacy code in 1.5
public String loophole(Integer x) {
List<String> ys = new ArrayList<String>();
List xs = ys;
xs.add(x); // compile-time unchecked warning
return ys.iterator().next();
}
31. Example of warnings given:
Unsafe type operation:
Should not assign expression of raw type List to type List<Foo>.
References to generic type List<E> should be parameterized.
Unsafe type operation:
The method bar(List<Foo>) in the type SimpleExample should not
be applied for the arguments (List). References to generic types
should be parameterized.
32. ...and even worse...
"Once a satisfactory product has been achieved,
further change may be counterproductive,
especially if the product is successful.
You have to know when to stop.”
Donald Norman
33. • A type parameter cannot be referenced in a static context
• Runtime type check with instanceof and casting on generic types have no meaning
• Arrays of generic types are not permitted
• For overloading, it is not enough to use wildcards for formal parameter types
• Generic classes can be extended
– The subclass provides the actual type parameters for the superclass
• For overriding, the return type of the method in the subclass can now be identical or
a subtype of the return type of the method in the superclass
• A generic class cannot be a subclass of Throwable
• Type parameters are allowed in the throws clause, but not for the parameter of the
catch block
• Varargs with a parameterized type are not legal
34. Introduction of characters with new special meaning
<, > ? T, E, ...
super &
”Programs must be written for people to read,
and only incidentally for machines to execute.”
Abelson and Sussman
35. Which ones will compile ?
a) Basket b = new Basket();
b) Basket b1 = new Basket<Fruit>();
c) Basket<Fruit> b2 = new Basket<Fruit>();
d) Basket<Apple> b3 = new Basket<Fruit>();
e) Basket<Fruit> b4 = new Basket<Apple>();
f) Basket<?> b5 = new Basket<Apple>();
g) Basket<Apple> b6 = new Basket<?>();
36. Thoughts and comments
Anyone ?
Is this a good thing or not ?
Is it an important feature of the language ?
What if this was included in the first version ?
Would the design be different/easier ?
Would users use it differently ?
When should we use it ? If we should, that is!
Why can’t we find other good examples, but the collection ones ?
38. ”There are two ways of constructing a software design:
One way is to make it so simple
that there are obviously no deficiencies,
and the other way is to make it so complicated
that there are no obvious deficiencies.
The first method is far more difficult.”
C. A. R. Hoare
Editor's Notes
Fra det første eksemplet, hvordan signatur klassene/interfacene som ble brukt blir definert
Java var ikke de første til å introdusere denne språk-featuren, vis kanskje med eksempel med templates i c++
Skriv ned resten av deklarasjonene på tavla... Eller ta dem høyt!
Et annet tilfelle på casting er ved uthenting av objekter fra JNDI-tre
Vis FAQ-siden til Angelika (http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html)
Vis javadoc på collection api’et (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html)
Hva er navnet på metoden ?
Hva tar metoden som parameter ???
Hvorfor er den blitt så kompleks ? Pga bakoverkomp – skal ikke være mer begrensende enn tidligere versjoner
FØRSTE PROBLEM!
En og en linje...
Ta på tavla – G&lt;Foo&gt; !subtype G&lt;Bar&gt;, selv om Foo subtype Bar (Bruk Basket/fruit/apple eksemplet)
Hva er feil med det nederste eksemplet ?
Collection of unknown: Collection&lt;?&gt;
Hva er feil med det nederste eksemplet ?
Collection of unknown: Collection&lt;?&gt;
Wildcard type
Vi kan fortsatt lese elementer og gi dem typen Object. Men...
Men, å assigne et Object til resultatet av get() er lov!
Før denne slide, gi eksempel-koden først
Hva betyr den første metoden ? Jo, f.eks. Kan vi ikke kalle på denne med List&lt;Apple&gt; (Apple er subtype av Fruit)
Hvorfor gir denne feil ?
Typen til den andre parameteren er en ukjent subtype av Fruit. Denne behøver ikke nødvendigvis være en supertype til Banana
Tegn bokser klasse-hierarki
Hvorfor gir denne feil ?
Typen til den andre parameteren er en ukjent subtype av Fruit. Denne behøver ikke nødvendigvis være en supertype til Banana
Tegn bokser klasse-hierarki
Spør publikum hvordan denne kan løses, og begynn å skriv metoden på tavla
...men bør overskriften egentlig være her ? Det kan være tull å introdusere alle ”ordene” i generics-ordboka...
Kanskje lettere å bare vise de ulike tingene ???
Spør publikum hvordan denne kan løses
Spør publikum hvordan denne kan løses
Kan man nå f.eks. ha en array av Stringer og en Collection av Objecter ? JA!
T definisjonen kan f.eks. også ha ”extends” og andre ting i seg!
Hvorfor er det nødvendig å kunne (eller bare å si) noe om dette her ?
Svar: Dårlig design/implementasjonen påvirker interfacet!
Vis hvordan koden ser ut etter å ha kjørt JAD. Erasior
True
Hvorfor gir denne feil ?
Unchecked warnings will occur
Vil gi feil i runtime!
Hentet fra foredrag på javazone... Var så morsom (fordi man blir bare helt oppgitt) at jeg måtte ta den med...
...og på neste slide til vedkommende, så står det med store bokstaver: ”GENERIC FUN HAS JUST BEGUN”
Why not ? Unntak er kjedelig (les: gjør ting vanskeligere)
Årsaken til noen her er erasure valget!
Kanskje bedre å tegne på tavla
Som er nesten definisjonen på økt kompleksitet/økt vanskelighet.
Og dette er bare for generics... Andre så som ”:” er også lagt til i 1.5